Intersection of Two Sorted Arrays
Last Updated :
11 Oct, 2024
Given two sorted arrays a[] and b[], the task is to return intersection. Intersection of two arrays is said to be elements that are common in both arrays. The intersection should not count duplicate elements and the result should contain items in sorted order.
Examples:
Input: a[] = {1, 1, 2, 2, 2, 4}, b[] = {2, 2, 4, 4}
Output: {2, 4}
Explanation: 2 and 4 are only common elements in both the arrays.
Input: a[] = {1, 2}, b[] = {3, 4}
Output: {}
Explanation: No common elements.
Input: a[] = {1, 2, 3}, b[] = {1, 2, 3}
Output: {1, 2, 3}
Explanation: All elements are common
[Naive Approach] Using Nested Loops - O(n*m) Time and O(1) Space
- Traverse through a[] and avoid duplicates while traversing. Since the arrays are sorted, we can avoid duplicates by matching with the previous element.
- For every element of a[], check if it is in b[], If Yes, then add it to the result and do not traverse further in b[] to avoid duplicates.
C++
#include <iostream>
#include <vector>
using namespace std;
// Function to find the intersection of two arrays
// It returns a vector containing the common elements
vector<int> intersection(vector<int>& a, vector<int>& b) {
vector<int> res;
int m = a.size();
int n = b.size();
for(int i = 0; i < m; i++) {
// Note that duplicates must be
// consecutive in a sorted array
if(i > 0 && a[i - 1] == a[i])
continue;
// Since we are only searchin distint
// elements of a[] in b[] and we break as
// soon we find a match, we get only
// distinct elements in result
for(int j = 0; j < n; j++) {
if(a[i] == b[j]) {
res.push_back(a[i]);
break;
}
}
}
return res;
}
int main() {
vector<int> a = {3, 5, 10, 10, 10, 15, 15, 20};
vector<int> b = {5, 10, 10, 15, 30};
vector<int> res = intersection(a, b);
for (int x : res) {
cout << x << " ";
}
}
C
#include <stdio.h>
// Function to find the intersection of two arrays
// It returns the result array containing the common elements
void intersection(int a[], int m, int b[], int n, int res[], int *res_size) {
for (int i = 0; i < m; i++) {
// Note that duplicates must be
// consecutive in a sorted array
if (i > 0 && a[i - 1] == a[i])
continue;
// Since we are only searching distinct
// elements of a[] in b[] and we break as
// soon we find a match, we get only
// distinct elements in result
for (int j = 0; j < n; j++) {
if (a[i] == b[j]) {
res[(*res_size)++] = a[i];
break;
}
}
}
}
int main() {
int a[] = {3, 5, 10, 10, 10, 15, 15, 20};
int b[] = {5, 10, 10, 15, 30};
int res[10];
int res_size = 0;
intersection(a, 8, b, 5, res, &res_size);
for (int i = 0; i < res_size; i++) {
printf("%d ", res[i]);
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to find the intersection of two arrays
// It returns a list containing the common elements
static List<Integer> intersection(int[] a, int[] b) {
List<Integer> res = new ArrayList<>();
int m = a.length;
int n = b.length;
for (int i = 0; i < m; i++) {
// Note that duplicates must be
// consecutive in a sorted array
if (i > 0 && a[i - 1] == a[i])
continue;
// Since we are only searching distinct
// elements of a[] in b[] and we break as
// soon we find a match, we get only
// distinct elements in result
for (int j = 0; j < n; j++) {
if (a[i] == b[j]) {
res.add(a[i]);
break;
}
}
}
return res;
}
public static void main(String[] args) {
int[] a = {3, 5, 10, 10, 10, 15, 15, 20};
int[] b = {5, 10, 10, 15, 30};
List<Integer> res = intersection(a, b);
for (int x : res) {
System.out.print(x + " ");
}
}
}
Python
# Function to find the intersection of two arrays
# It returns a list containing the common elements
def intersection(a, b):
res = []
m = len(a)
n = len(b)
for i in range(m):
# Note that duplicates must be
# consecutive in a sorted array
if i > 0 and a[i - 1] == a[i]:
continue
# Since we are only searching distinct
# elements of a[] in b[] and we break as
# soon we find a match, we get only
# distinct elements in result
for j in range(n):
if a[i] == b[j]:
res.append(a[i])
break
return res
# Driver code
a = [3, 5, 10, 10, 10, 15, 15, 20]
b = [5, 10, 10, 15, 30]
res = intersection(a, b)
print(" ".join(map(str, res)))
C#
using System;
using System.Collections.Generic;
class GfG
{
// Function to find the intersection of two arrays
// It returns a list containing the common elements
static List<int> Intersection(int[] a, int[] b)
{
List<int> res = new List<int>();
int m = a.Length;
int n = b.Length;
for (int i = 0; i < m; i++)
{
// Note that duplicates must be
// consecutive in a sorted array
if (i > 0 && a[i - 1] == a[i])
continue;
// Since we are only searching distinct
// elements of a[] in b[] and we break as
// soon we find a match, we get only
// distinct elements in result
for (int j = 0; j < n; j++)
{
if (a[i] == b[j])
{
res.Add(a[i]);
break;
}
}
}
return res;
}
static void Main()
{
int[] a = { 3, 5, 10, 10, 10, 15, 15, 20 };
int[] b = { 5, 10, 10, 15, 30 };
List<int> res = Intersection(a, b);
foreach (int x in res)
{
Console.Write(x + " ");
}
}
}
JavaScript
// Function to find the intersection of two arrays
// It returns an array containing the common elements
function intersection(a, b) {
let res = [];
let m = a.length;
let n = b.length;
for (let i = 0; i < m; i++) {
// Note that duplicates must be
// consecutive in a sorted array
if (i > 0 && a[i - 1] === a[i]) {
continue;
}
// Since we are only searching distinct
// elements of a[] in b[] and we break as
// soon we find a match, we get only
// distinct elements in result
for (let j = 0; j < n; j++) {
if (a[i] === b[j]) {
res.push(a[i]);
break;
}
}
}
return res;
}
// Driver code
let a = [3, 5, 10, 10, 10, 15, 15, 20];
let b = [5, 10, 10, 15, 30];
let res = intersection(a, b);
console.log(res.join(" "));
Approaches Same as Unsorted Arrays - Best Time O(n+m) and O(n) Space
We have discussed different approaches for intersection of unsorted arrays. We can use the same approaches here. The best performance that we can achieve using the same approaches is O(n+m) Time and O(n) Auxiliary Space for hash set. Please note that in these approaches we do not use the fact that input arrays are sorted.
[Expected Approach] Using Merge Step of Merge Sort - O(n+m) Time and O(1) Space
The idea is based one merge function to merge two sorted arrays.
- We simultaneously traverse both a[] and b[] from the left side. While traversing, we avoid duplicates in a[]. We do not need to do it for b[] because once we have a match, we move ahead in a[] and b[] both.
- If current elements are not same, we skip the smaller of the two. If current element of a[] is smaller, we move ahead in a[] and if current of b[] is smaller, we move ahead in b[].
- Else (If same), we add one occurrence of the current element to the result and move ahead in both a[] and b[].
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> intersection(vector<int>& a, vector<int>& b) {
vector<int> res;
int m = a.size();
int n = b.size();
// This is similar to merge of merge sort
int i = 0, j = 0;
while(i < m && j < n) {
// Skip duplicate elements in the first array
if(i > 0 && a[i - 1] == a[i]) {
i++;
continue;
}
// Skip the smaller
if(a[i] < b[j]) {
i++;
}
else if(a[i] > b[j]) {
j++;
}
// If equal, add to result and move both
else {
res.push_back(a[i]);
i++;
j++;
}
}
return res;
}
int main() {
vector<int> a = {3, 5, 10, 10, 10, 15, 15, 20};
vector<int> b = {5, 10, 10, 15, 30};
vector<int> res = intersection(a, b);
for (int x : res) {
cout << x << " ";
}
}
C
#include <stdio.h>
// Function to find the intersection of two arrays
void intersection(int a[], int m, int b[], int n, int res[], int *res_size) {
int i = 0, j = 0;
// This is similar to merge of merge sort
while (i < m && j < n) {
// Skip duplicate elements in the first array
if (i > 0 && a[i - 1] == a[i]) {
i++;
continue;
}
// Skip the smaller
if (a[i] < b[j]) {
i++;
} else if (a[i] > b[j]) {
j++;
}
// If equal, add to result and move both
else {
res[(*res_size)++] = a[i];
i++;
j++;
}
}
}
int main() {
int a[] = {3, 5, 10, 10, 10, 15, 15, 20};
int b[] = {5, 10, 10, 15, 30};
int res[10];
int res_size = 0;
// Correctly call the intersection function
intersection(a, 8, b, 5, res, &res_size);
for (int i = 0; i < res_size; i++) {
printf("%d ", res[i]);
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to find the intersection of two arrays
static List<Integer> intersection(int[] a, int[] b) {
List<Integer> res = new ArrayList<>();
int m = a.length;
int n = b.length;
// This is similar to merge of merge sort
int i = 0, j = 0;
while (i < m && j < n) {
// Skip duplicate elements in the first array
if (i > 0 && a[i - 1] == a[i]) {
i++;
continue;
}
// Skip the smaller
if (a[i] < b[j]) {
i++;
} else if (a[i] > b[j]) {
j++;
}
// If equal, add to result and move both
else {
res.add(a[i]);
i++;
j++;
}
}
return res;
}
public static void main(String[] args) {
int[] a = {3, 5, 10, 10, 10, 15, 15, 20};
int[] b = {5, 10, 10, 15, 30};
List<Integer> res = intersection(a, b);
for (int x : res) {
System.out.print(x + " ");
}
}
}
Python
# Function to find the intersection of two arrays
def intersection(a, b):
res = []
m = len(a)
n = len(b)
# This is similar to merge of merge sort
i, j = 0, 0
while i < m and j < n:
# Skip duplicate elements in the first array
if i > 0 and a[i - 1] == a[i]:
i += 1
continue
# Skip the smaller
if a[i] < b[j]:
i += 1
elif a[i] > b[j]:
j += 1
# If equal, add to result and move both
else:
res.append(a[i])
i += 1
j += 1
return res
# Driver code
a = [3, 5, 10, 10, 10, 15, 15, 20]
b = [5, 10, 10, 15, 30]
res = intersection(a, b)
print(" ".join(map(str, res)))
C#
using System;
using System.Collections.Generic;
class GfG
{
// Function to find the intersection of two arrays
static List<int> Intersection(int[] a, int[] b)
{
List<int> res = new List<int>();
int m = a.Length;
int n = b.Length;
// This is similar to merge of merge sort
int i = 0, j = 0;
while (i < m && j < n)
{
// Skip duplicate elements in the first array
if (i > 0 && a[i - 1] == a[i])
{
i++;
continue;
}
// Skip the smaller
if (a[i] < b[j])
{
i++;
}
else if (a[i] > b[j])
{
j++;
}
// If equal, add to result and move both
else
{
res.Add(a[i]);
i++;
j++;
}
}
return res;
}
static void Main()
{
int[] a = { 3, 5, 10, 10, 10, 15, 15, 20 };
int[] b = { 5, 10, 10, 15, 30 };
List<int> res = Intersection(a, b);
foreach (int x in res)
{
Console.Write(x + " ");
}
}
}
JavaScript
// Function to find the intersection of two arrays
function intersection(a, b) {
let res = [];
let m = a.length;
let n = b.length;
// This is similar to merge of merge sort
let i = 0, j = 0;
while (i < m && j < n) {
// Skip duplicate elements in the first array
if (i > 0 && a[i - 1] === a[i]) {
i++;
continue;
}
// Skip the smaller
if (a[i] < b[j]) {
i++;
} else if (a[i] > b[j]) {
j++;
}
// If equal, add to result and move both
else {
res.push(a[i]);
i++;
j++;
}
}
return res;
}
// Driver code
let a = [3, 5, 10, 10, 10, 15, 15, 20];
let b = [5, 10, 10, 15, 30];
let res = intersection(a, b);
console.log(res.join(" "));
Time Complexity: O(n+m), where n and m is the size of a[] and b[] respectively.
Auxiliary Space: O(1)
Related Articles:
Similar Reads
Intersection of two Arrays Given two arrays a[] and b[], find their intersection â the unique elements that appear in both. Ignore duplicates, and the result can be in any order.Input: a[] = [1, 2, 1, 3, 1], b[] = [3, 1, 3, 4, 1]Output: [1, 3]Explanation: 1 and 3 are the only common elements and we need to print only one occu
12 min read
Merge two sorted arrays Given two sorted arrays, the task is to merge them in a sorted manner.Examples: Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8} Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8}Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8} Output: arr3[] = {4, 5, 7, 8, 8, 9} Table of Content[Naive Approach] Concatenat
10 min read
Intersection of Two Sorted Arrays with Distinct Elements Given two sorted arrays a[] and b[] with distinct elements of size n and m respectively, the task is to find intersection (or common elements) of the two arrays. We need to return the intersection in sorted order.Note: Intersection of two arrays can be defined as a set containing distinct common ele
13 min read
K-th Element of Merged Two Sorted Arrays Given two sorted arrays of sizes m and n respectively, the task is to find the element that would be at the k-th position in the final sorted array formed by merging these two arrays.Examples: Input: a[] = [2, 3, 6, 7, 9], b[] = [1, 4, 8, 10], k = 5Output: 6Explanation: The final sorted array is [1,
15+ min read
Median of two Sorted Arrays of Different Sizes Given two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays. Assume that the two sorted arrays are merged and then median is selected from the combined array.This is an extension of Median of two sorted arrays of equal size problem. Here we handle arrays of unequal si
15+ min read