Intersection of Two Sorted Arrays
Given two sorted arrays arr1[] and arr2[], return the intersection of both arrays.
The intersection is the set of elements that are common in both arrays. It must not contain duplicates. If there is no common element, return an empty array.
Constraints:
1 <= arr1.size(), arr2.size() <= 10^51 <= arr1[i], arr2[i] <= 10^6
Brute Force
For every value in arr1, search the whole of arr2 to see if it is there.
- Go through
arr1one value at a time. - If the value is the same as the last value in
result, skip it.arr1is sorted, so a duplicate sits right next to its copy. - Otherwise, scan
arr2from the start. - If you find the value, add it to
resultand stop scanning. - Return
result.
This works, but for each value of arr1 we may scan all of arr2. It ignores that both arrays are sorted.
class Solution {public:vector<int> intersection(vector<int>& arr1, vector<int>& arr2) {int n = arr1.size();int m = arr2.size();vector<int> result;for (int i = 0; i < n; i++) {if (!result.empty() && result.back() == arr1[i]) {continue;}for (int j = 0; j < m; j++) {if (arr1[i] == arr2[j]) {result.push_back(arr1[i]);break;}}}return result;}};
- Time: O(n * m). For each value of
arr1, we may scan all ofarr2. - Space: O(1) extra, not counting the output array.
Optimal Approach: Two Pointers
Both arrays are sorted, so we can walk through them together with one pointer on each.
We use:
i: pointer onarr1.j: pointer onarr2.
At each step, compare arr1[i] and arr2[j]:
arr1[i] < arr2[j]:arr1[i]is too small. It cannot be inarr2anymore. Moveiforward.arr1[i] > arr2[j]:arr2[j]is too small. Movejforward.- Equal: we found a common value. Add it to
resultonly ifresultis empty or its last value is different (this skips duplicates). Move both pointers forward.
Stop when either array is finished, because nothing more can match.
class Solution {public:vector<int> intersection(vector<int>& arr1, vector<int>& arr2) {int n = arr1.size();int m = arr2.size();int i = 0;int j = 0;vector<int> result;while (i < n && j < m) {if (arr1[i] < arr2[j]) {i++;} else if (arr1[i] > arr2[j]) {j++;} else {if (result.empty() || result.back() != arr1[i]) {result.push_back(arr1[i]);}i++;j++;}}return result;}};
Complexity
Every step moves at least one pointer forward, so each element of both arrays is looked at at most once.
Besides the output array, we only use the pointers i and j. The output holds at most min(n, m) values.