VOOZH about

URL: https://www.geeksforgeeks.org/dsa/intersection-of-two-sorted-arrays/

⇱ Intersection of Two Sorted Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Intersection of Two Sorted Arrays

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

[Naive Approach] Using Nested Loops - O(n*m) Time and O(1) Space

  1. Traverse through a[] and avoid duplicates while traversing. Since the arrays are sorted, we can avoid duplicates by matching with the previous element.
  2. 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.

Output
2 4 

[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.

  1. 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.
  2. 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[].
  3. Else (If same), we add one occurrence of the current element to the result and move ahead in both a[] and b[].

Output
2 4 

Related Articles:

Comment