VOOZH about

URL: https://www.geeksforgeeks.org/dsa/common-elements-in-two-sorted-arrays/

⇱ Common Elements in Two Sorted Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Common Elements in Two Sorted Arrays

Last Updated : 23 Jul, 2025

Given two sorted arrays a[] and b[]. The task is to return the common elements of both arrays. If an element appears more than once in both array, we need to pick minimum of its two frequencies

Examples:

Input: a[] = [1, 1, 2, 2, 2, 4], b[] = [2, 2, 4, 4]
Output: [2, 2, 4]
Explanation: 2 and 4 are only common elements and 2 appears two times in both arrays.

Input: a[] = [1, 2], b[] = [3, 4]
Output: []
Explanation: No common elements.

Input: a[] = [1, 1, 1], b[] = [1, 1, 1, 1]
Output: [1, 1, 1]

Approaches Same as Unsorted Arrays - Best Time O(n) and O(n) Space

We have discussed different approaches for common of two unsorted arrays. We can use the same approaches here. The best performance that we can achieve using the same approaches is O(n) 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,

Using Merge of Merge Sort - O(n) 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.
  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. If same, we keep adding while elements are same.

Output
1 2 4 

Illustration of the Above Approach:

Input : a = {1, 2, 2, 2, 3}, b = {2, 2, 4}

Initialization:

  • i = 0, j = 0, res = []
  • i points to elements in array a[] and j points to elements in array b[].

Iterations inside the while loop:

1st Iteration:

  • a[i] = 1, b[j] = 2
  • a[i] is smaller, so skip the smaller element in a[].
  • i = 1, j = 0

2nd Iteration:

  • a[i] = 2, b[j] = 2
  • Since a[i] is equal to b[j], both arrays have this common element. So we keep adding to result while matching.
  • res = [2, 2]
  • i = 3, j = 2

3rd Iteration:

  • a[i] = 2, b[j] = 4
  • Since a[i] is smaller than b[j], skip the smaller element in a[] by incrementing i.
  • Update:i = 4, j = 2

4th Iteration:

  • a[i] = 3, b[j] = 4
  • Since a[i] is smaller than b[j], skip the smaller element in a[] by incrementing i.
  • Update:i = 5, j = 2
Comment