Intersection of Two Sorted Arrays (original) (raw)
Last Updated : 8 Apr, 2026
Given two **sorted arrays **a[] and **b[], where each array may contain **duplicate elements , return the elements in the **intersection of the two arrays. **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
Table of Content
- [Naive Approach] Using Nested Loops - O(n*m) Time and O(1) Space
- [Expected Approach] Using Merge Step of Merge Sort - O(n+m) Time and O(1) Space
[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 #include using namespace std;
// Function to find the intersection of two arrays // It returns a vector containing the common elements vector intersection(vector& a, vector& b) { vector 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 a = {1, 1, 2, 2, 2, 4};
vector b = {2, 2, 4, 4};
vector res = intersection(a, b);
for (int x : res) {
cout << x << " ";
}
}
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 = {1, 1, 2, 2, 2, 4};
int[] b = {2, 2, 4, 4};
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 resa = [1, 1, 2, 2, 2, 4] b = [2, 2, 4, 4] 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 Intersection(int[] a, int[] b) { List res = new List(); 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 = {1, 1, 2, 2, 2, 4};
int[] b = {2, 2, 4, 4};
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 = [1, 1, 2, 2, 2, 4]; let b = [2, 2, 4, 4]; let res = intersection(a, b);
console.log(res.join(" "));
`
[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 using namespace std;
vector intersection(vector& a, vector& b) { vector res; int m = a.size(); int n = b.size();
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 a = {1, 1, 2, 2, 2, 4}; vector b = {2, 2, 4, 4}; vector res = intersection(a, b); for (int x : res) { cout << x << " "; } }
Java
import java.util.ArrayList; import java.util.List;
class GfG {
static List<Integer> intersection(int[] a, int[] b) {
List<Integer> res = new ArrayList<>();
int m = a.length;
int n = b.length;
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 = {1, 1, 2, 2, 2, 4};
int[] b = {2, 2, 4, 4};
List<Integer> res = intersection(a, b);
for (int x : res) {
System.out.print(x + " ");
}
}}
Python
def intersection(a, b): res = [] m = len(a) n = len(b)
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 resDriver code
a = [1, 1, 2, 2, 2, 4] b = [2, 2, 4, 4] res = intersection(a, b) print(" ".join(map(str, res)))
C#
using System; using System.Collections.Generic;
class GfG { static List Intersection(int[] a, int[] b) { List res = new List(); int m = a.Length; int n = b.Length;
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 = {1, 1, 2, 2, 2, 4};
int[] b = {2, 2, 4, 4};
List<int> res = Intersection(a, b);
foreach (int x in res)
{
Console.Write(x + " ");
}
}}
JavaScript
function intersection(a, b) { let res = []; let m = a.length; let n = b.length;
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 = [1, 1, 2, 2, 2, 4]; let b = [2, 2, 4, 4]; let res = intersection(a, b);
console.log(res.join(" "));
`
**Related Articles: