Skip to content

1213. Intersection of Three Sorted Arrays 👍

  • Time: $O(|\texttt{arr1}| + |\texttt{arr2}| + |\texttt{arr3}|)$
  • Space: $O(\min(|\texttt{arr1}|, |\texttt{arr2}|, |\texttt{arr3}|))$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
 public:
  vector<int> arraysIntersection(vector<int>& arr1, vector<int>& arr2,
                                 vector<int>& arr3) {
    vector<int> ans;
    int i = 0;
    int j = 0;
    int k = 0;

    while (i < arr1.size() && j < arr2.size() && k < arr3.size()) {
      const int mn = min({arr1[i], arr2[j], arr3[k]});
      if (arr1[i] == mn && arr2[j] == mn && arr3[k] == mn) {
        ans.push_back(mn);
        ++i;
        ++j;
        ++k;
      } else if (arr1[i] == mn) {
        ++i;
      } else if (arr2[j] == mn) {
        ++j;
      } else {
        ++k;
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public List<Integer> arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
    List<Integer> ans = new ArrayList<>();
    int i = 0;
    int j = 0;
    int k = 0;

    while (i < arr1.length && j < arr2.length && k < arr3.length) {
      final int mn = Math.min(arr1[i], Math.min(arr2[j], arr3[k]));
      if (arr1[i] == mn && arr2[j] == mn && arr3[k] == mn) {
        ans.add(mn);
        ++i;
        ++j;
        ++k;
      } else if (arr1[i] == mn) {
        ++i;
      } else if (arr2[j] == mn) {
        ++j;
      } else {
        ++k;
      }
    }

    return ans;
  }
}