find common elements In 3 sorted arrays
Pattern: Two pointers
Walk three sorted arrays at once. When all fronts are equal, record the value; otherwise move past the smallest front.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
You are given three arrays, each sorted in non-decreasing order. Return the values that appear in all three, each value
once, in increasing order. For example, [1, 5, 10, 20, 40, 80], [6, 7, 20, 80, 100] and
[3, 4, 15, 20, 30, 70, 80, 120] have 20 and 80 in common.
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name
commonElements and the "each value once" rule are this guide's own.
Think first
- With two sorted arrays, you moved past the smaller front. With three, which front can safely be dropped?
- When all three fronts are equal, what do you do?
- How do you avoid reporting a value twice when it repeats in all three arrays?
Hints
Brute force, and why it fails
For each value of the first array, binary search the other two: O(n log m). Intersecting three hash sets is O(n + m + p) with extra memory. Three pointers need no extra memory and use the order directly.
The key insight
The two-array intersection walk extends to three arrays: the smallest front is always hopeless, so drop it. Every step moves at least one pointer, so the walk is linear in the total length.
Dry run
| b[j] | 6 |
|---|---|
| c[k] | 3 |
a = [1, 5, 10, 20, 40, 80], b = [6, 7, 20, 80, 100] and c = [3, 4, 15, 20, 30, 70, 80, 120]. The fronts are 1, 6 and 3. The smallest, 1, cannot be common, so move a on.
The plan
result = empty list
i = j = k = 0
while i < len(a) and j < len(b) and k < len(c):
if a[i] == b[j] == c[k]:
if result is empty or last of result != a[i]: append a[i]
i, j, k = i + 1, j + 1, k + 1
else if a[i] is the smallest front: i = i + 1
else if b[j] is the smallest of b[j] and c[k]: j = j + 1
else: k = k + 1
return result
Complexity
- Time
O(n + m + p)- Space
O(1)
Each step moves at least one pointer. Besides the result, only three indexes are used.
Edge cases
- No common value: an empty list.
- A value repeated in all three arrays, as in 5 in
[1, 5, 5],[3, 4, 5, 5, 10]and[5, 5, 10, 20]: reported once. - One array empty: an empty list.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> commonElements(int[] a, int[] b, int[] c) {
List<Integer> result = new ArrayList<>();
int i = 0;
int j = 0;
int k = 0;
while (i < a.length && j < b.length && k < c.length) {
if (a[i] == b[j] && b[j] == c[k]) {
if (result.isEmpty() || result.get(result.size() - 1) != a[i]) {
result.add(a[i]); // each common value once
}
i++;
j++;
k++;
} else if (a[i] <= b[j] && a[i] <= c[k]) {
i++; // move whichever front is smallest
} else if (b[j] <= c[k]) {
j++;
} else {
k++;
}
}
return result;
}
}C++
class Solution {
public:
vector<int> commonElements(vector<int>& a, vector<int>& b, vector<int>& c) {
vector<int> result;
size_t i = 0;
size_t j = 0;
size_t k = 0;
while (i < a.size() && j < b.size() && k < c.size()) {
if (a[i] == b[j] && b[j] == c[k]) {
if (result.empty() || result.back() != a[i]) {
result.push_back(a[i]); // each common value once
}
i++;
j++;
k++;
} else if (a[i] <= b[j] && a[i] <= c[k]) {
i++; // move whichever front is smallest
} else if (b[j] <= c[k]) {
j++;
} else {
k++;
}
}
return result;
}
};Python
class Solution:
def commonElements(self, a, b, c):
result = []
i = j = k = 0
while i < len(a) and j < len(b) and k < len(c):
if a[i] == b[j] == c[k]:
if not result or result[-1] != a[i]:
result.append(a[i]) # each common value once
i += 1
j += 1
k += 1
elif a[i] <= b[j] and a[i] <= c[k]:
i += 1 # move whichever front is smallest
elif b[j] <= c[k]:
j += 1
else:
k += 1
return resultCommon mistakes
- Moving a pointer that is not the smallest, which can skip a common value.
- Reporting repeated common values more than once.
- Stopping when only one array runs out, but checking the wrong condition.