Intersection of Two Arrays
Find the unique values two arrays share by sorting both and walking them together with one pointer each.
01The problem
Return the unique values that appear in both arrays. Each value appears once in the result, no matter how many times it repeats. Any order is fine.
| nums1 | nums2 | Output |
|---|---|---|
[1, 2, 2, 1] | [2, 2] | [2] |
[4, 9, 5] | [9, 4, 9, 8, 4] | [4, 9] |
Constraints: 1 to 1000 values each, values 0 to 1000.
02How to spot it
- Values in both arrays: an intersection.
- Each value once.
- Sorting both lets you walk them together, like merging.
03Pseudocode
sort a ; sort b
i = 0 ; j = 0
while i < len(a) and j < len(b):
if a[i] < b[j]: i += 1
elif a[i] > b[j]: j += 1
else: add a[i] if not just added
i += 1 ; j += 1- Sort both arrays.
- Move the pointer at the smaller value.
- Equal? Record it once, move both.
04Watch it work
a (sorted)
b (sorted)
out
Sort both arrays. Now equal values line up, and we can walk both with one pointer each.
Pseudocode
- sort a ; sort b
- i = 0 ; j = 0
- while i < len(a) and j < len(b):
- if a[i] < b[j]: i += 1
- elif a[i] > b[j]: j += 1
- else: add a[i] if not just added
- i += 1 ; j += 1
Variables
- i
- 0
- j
- 0
05Step-by-step dry run
- 1
a (sorted)
405192ib (sorted)
4041829394jout
Sort both arrays. Now equal values line up, and we can walk both with one pointer each.
i = 0j = 0
- 2
a (sorted)
405192ib (sorted)
4041829394jout
404 = 4: a common value. Record 4 and move both.
i = 0j = 0out = [4]
- 3
a (sorted)
405192ib (sorted)
4041829394jout
405 > 4: move j to find a bigger value in b.
i = 1j = 1
- 4
a (sorted)
405192ib (sorted)
4041829394jout
405 < 8: 5 can't match anything further in b (only bigger values). Move i.
i = 1j = 2
- 5
a (sorted)
405192ib (sorted)
4041829394jout
409 > 8: move j to find a bigger value in b.
i = 2j = 2
- 6
a (sorted)
405192ib (sorted)
4041829394jout
40919 = 9: a common value. Record 9 and move both.
i = 2j = 3out = [4, 9]
- 7
a (sorted)
405192b (sorted)
4041829394jout
4091One array has run out, so nothing else can match. The answer is [4, 9].
out = [4, 9]
06Java solution
import java.util.*;
public class IntersectionUnique {
static int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer> out = new ArrayList<>();
int i = 0, j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] < nums2[j]) i++;
else if (nums1[i] > nums2[j]) j++;
else {
int v = nums1[i];
boolean isNew = out.isEmpty() || out.get(out.size() - 1) != v;
if (isNew) out.add(v); // skip repeated matches
i++;
j++;
}
}
int[] res = new int[out.size()];
for (int k = 0; k < res.length; k++) res[k] = out.get(k);
return res;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(intersection(new int[] {4, 9, 5}, new int[] {9, 4, 9, 8, 4})));
System.out.println(Arrays.toString(intersection(new int[] {1, 2, 2, 1}, new int[] {2, 2})));
System.out.println(Arrays.toString(intersection(new int[] {0, 5, 3}, new int[] {3, 0, 0})));
}
}[4, 9] [2] [0, 3]
Tricky lines, decoded
out.get(out.size() - 1) != v: sorted order puts duplicates of a match back to back, so checking the last added value is enough.vis anint, so this compares numbers, not objects.Arrays.sortis O(n log n). Without sorting, use aHashSetinstead.
07Why it works
After sorting, the smaller of a[i] and b[j] can't match anything further along in the other array, which only holds bigger values, so skipping it is safe. Equal values are common, and because duplicates are adjacent, comparing with the last recorded value keeps each one unique.
Invariant: every common value smaller than min(a[i], b[j]) is already in out, exactly once.
08Time and space
- Time: O(n log n + m log m). Sorting dominates; the walk is O(n + m).
- Space: O(1) not counting the output and the sort's own memory.
09Edge cases
| Input | Output | Why it matters |
|---|---|---|
[1] and [2] | [] | nothing in common |
[1, 1, 1] and [1] | [1] | unique output |
[0, 5, 3] and [3, 0, 0] | [0, 3] | zero is a value |
[7, 8] and [9, 10] | [] | disjoint ranges |
[1, 2, 2, 1] and [2, 2] | [2] | duplicates collapse |
10Common mistakes
- Adding every match. Returns
[2, 2]instead of[2]: skip a value equal to the last one added. - Forgetting to sort. The walk only works on sorted input.
- Comparing
Integerobjects with!=. Object comparison fails above 127: unbox toint vfirst.
11Other approaches
| Approach | Time | Space | Use when |
|---|---|---|---|
| Two HashSets | O(n + m) | O(n + m) | Fastest when memory is fine |
| Sort + two pointers | O(n log n) | O(1) | Memory matters, or already sorted |
| Sort one + binary search | O(m log n) | O(1) | One array is tiny |
Streams retainAll | O(n + m) | O(n) | Production code |
12In the interview
- Keep duplicates? That's problem 9, Intersection of Two Arrays II: count instead of dedupe.
- k arrays? Intersect pairwise, smallest first, or count values across k sets.
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. a[i] = 5 and b[j] = 8. What moves?
2. Why is checking only the last added value enough to avoid duplicates?
14Solve it yourself
Try it on LeetCode #349.