Intersection of Two Sorted Arrays

easy

Given two sorted arrays arr1 and arr2, return their intersection — the set of values that appear in both arrays.

The result must contain no duplicates: even if a value repeats inside either array, it appears at most once in the answer. Return the common values in ascending order (the natural order you get by walking the sorted inputs).

If the arrays share nothing, return an empty array.

Hints

You only care whether a value shows up in both arrays — and each shared value should be counted just once.
The brute-force double loop never uses the fact that both arrays are already sorted. That's a hint there's a faster way.
Put a pointer at the start of each array. Advance the pointer at the smaller value; when both match, record it and advance both.

Common doubts

The intersection is a set of common values. Even if 2 appears three times in both arrays, it belongs in the answer exactly once.
Return the common values in ascending order. Walking both sorted arrays left-to-right produces exactly that order for free.
Return an empty array. The two-pointer loop simply exits without ever recording a match.

Interview follow-ups

You'd lose the two-pointer trick. Either sort both first (O(n log n)) or build a hash set from the smaller array and probe with the larger (O(n+m) time, O(min(n,m)) space).
Generalize the merge with k pointers and a min-heap, or intersect them pairwise, shrinking the running result each time.

Fun facts

  • The two-pointer merge here is the exact same 'advance the smaller' step that drives the merge phase of merge sort.
  • Database engines use this precise sorted-merge-intersection when joining two indexes that are already ordered by the join key.

Asked at

AmazonGoogleMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: arr1 = [1, 2, 3, 4], arr2 = [2, 4, 6, 7, 8]
Output: [2, 4]
2 and 4 are the only values present in both arrays.
Example 2
Input: arr1 = [1, 2, 2, 3, 4], arr2 = [2, 2, 4, 6, 7, 8]
Output: [2, 4]
2 and 4 are common; duplicates are collapsed to a single copy each.
Example 3
Input: arr1 = [1, 2], arr2 = [3, 4]
Output: []
The arrays share no values, so the intersection is empty.
Constraints

- 1 <= arr1.size, arr2.size <= 10^5 - 1 <= arr1[i], arr2[i] <= 10^6 - arr1 is sorted in ascending order - arr2 is sorted in ascending order

Solve this problem →