Intersection of two sorted arrays
Pattern: Two pointers
Walk both sorted arrays together. Move past the smaller front value, and when the fronts match, take the value and move both.
The problem
You are given two arrays, each sorted in non-decreasing order. Return the values they have in common, in increasing order,
where repeats are matched one to one: a value appears as many times as it appears in both. For example, [1, 2, 2, 3] and
[2, 2, 4] give [2, 2], while [1, 1, 1] and [1] give [1].
On the original site the problem is written a little differently, so use the link above for its exact wording, which may
count repeats differently. The function name intersectionArray and the "repeats matched" rule are this guide's own.
Think first
- If
a[i]is smaller thanb[j], cana[i]still match anything later inb? - When the fronts are equal, what do you do with both pointers?
- How does this handle a value that appears twice in one array and once in the other?
Hints
Brute force, and why it fails
For each value of a, search b for an unused equal value: O(n × m). A hash map of counts works in O(n + m) but ignores
the sorted order and uses extra memory. Two pointers use the order directly.
The key insight
In sorted arrays, the smaller of the two front values can never be matched later, so it can be dropped at once. Each step drops or matches something, so the walk takes at most n + m steps.
Dry run
| j | 0 (value 2) |
|---|---|
| result | [] |
a = [1, 2, 2, 3] and b = [2, 2, 4]. 1 is smaller than 2, and 1 cannot appear later in b, so move i.
The plan
result = empty list
i = 0, j = 0
while i < len(a) and j < len(b):
if a[i] < b[j]: i = i + 1
else if a[i] > b[j]: j = j + 1
else:
append a[i] to result
i = i + 1; j = j + 1
return result
Complexity
- Time
O(n + m)- Space
O(min(n, m))
Each step moves at least one pointer. The result is at most as long as the shorter array.
Edge cases
- No common values: an empty list.
[1, 1, 1]and[1]: one 1, since only one pair can be matched.- One array empty: an empty list.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> intersectionArray(int[] a, int[] b) {
List<Integer> result = new ArrayList<>();
int i = 0;
int j = 0;
while (i < a.length && j < b.length) {
if (a[i] < b[j]) {
i++; // a[i] cannot appear later in b
} else if (a[i] > b[j]) {
j++;
} else {
result.add(a[i]); // a match uses one copy from each
i++;
j++;
}
}
return result;
}
}C++
class Solution {
public:
vector<int> intersectionArray(vector<int>& a, vector<int>& b) {
vector<int> result;
size_t i = 0;
size_t j = 0;
while (i < a.size() && j < b.size()) {
if (a[i] < b[j]) {
i++; // a[i] cannot appear later in b
} else if (a[i] > b[j]) {
j++;
} else {
result.push_back(a[i]); // a match uses one copy from each
i++;
j++;
}
}
return result;
}
};Python
class Solution:
def intersectionArray(self, a, b):
result = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] < b[j]:
i += 1 # a[i] cannot appear later in b
elif a[i] > b[j]:
j += 1
else:
result.append(a[i]) # a match uses one copy from each
i += 1
j += 1
return resultCommon mistakes
- Moving only one pointer on a match, which matches the same element twice.
- Adding each common value only once when the problem wants repeats matched (or the other way round). Read which rule your platform uses.
- Using
<=and skipping a value that would have matched.