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 mini = min({arr1[i], arr2[j], arr3[k]});
      if (arr1[i] == mini && arr2[j] == mini && arr3[k] == mini) {
        ans.push_back(mini);
        ++i;
        ++j;
        ++k;
      } else if (arr1[i] == mini) {
        ++i;
      } else if (arr2[j] == mini) {
        ++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 min = Math.min(arr1[i], Math.min(arr2[j], arr3[k]));
      if (arr1[i] == min && arr2[j] == min && arr3[k] == min) {
        ans.add(min);
        ++i;
        ++j;
        ++k;
      } else if (arr1[i] == min) {
        ++i;
      } else if (arr2[j] == min) {
        ++j;
      } else {
        ++k;
      }
    }

    return ans;
  }
}
Back to top