Intersection of Three Sorted Arrays

easy array three pointers sorted

Problem

Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays.

Inputarr1 = [1, 2, 3, 4, 5], arr2 = [1, 2, 5, 7, 9], arr3 = [1, 3, 4, 5, 8]
Output[1, 5]
Only 1 and 5 appear in all three arrays.

def arrays_intersection(arr1, arr2, arr3):
    i = j = k = 0
    res = []
    while i < len(arr1) and j < len(arr2) and k < len(arr3):
        if arr1[i] == arr2[j] == arr3[k]:
            res.append(arr1[i])
            i += 1; j += 1; k += 1
        else:
            m = max(arr1[i], arr2[j], arr3[k])
            if arr1[i] < m: i += 1
            if arr2[j] < m: j += 1
            if arr3[k] < m: k += 1
    return res
function arraysIntersection(arr1, arr2, arr3) {
  let i = 0, j = 0, k = 0;
  const res = [];
  while (i < arr1.length && j < arr2.length && k < arr3.length) {
    if (arr1[i] === arr2[j] && arr2[j] === arr3[k]) {
      res.push(arr1[i]);
      i++; j++; k++;
    } else {
      const m = Math.max(arr1[i], arr2[j], arr3[k]);
      if (arr1[i] < m) i++;
      if (arr2[j] < m) j++;
      if (arr3[k] < m) k++;
    }
  }
  return res;
}
class Solution {
    public List<Integer> arraysIntersection(int[] a1, int[] a2, int[] a3) {
        List<Integer> res = new ArrayList<>();
        int i = 0, j = 0, k = 0;
        while (i < a1.length && j < a2.length && k < a3.length) {
            if (a1[i] == a2[j] && a2[j] == a3[k]) {
                res.add(a1[i]);
                i++; j++; k++;
            } else {
                int m = Math.max(a1[i], Math.max(a2[j], a3[k]));
                if (a1[i] < m) i++;
                if (a2[j] < m) j++;
                if (a3[k] < m) k++;
            }
        }
        return res;
    }
}
vector<int> arraysIntersection(vector<int>& a1, vector<int>& a2, vector<int>& a3) {
    vector<int> res;
    int i = 0, j = 0, k = 0;
    while (i < (int)a1.size() && j < (int)a2.size() && k < (int)a3.size()) {
        if (a1[i] == a2[j] && a2[j] == a3[k]) {
            res.push_back(a1[i]);
            i++; j++; k++;
        } else {
            int m = max(a1[i], max(a2[j], a3[k]));
            if (a1[i] < m) i++;
            if (a2[j] < m) j++;
            if (a3[k] < m) k++;
        }
    }
    return res;
}
Time: O(n1 + n2 + n3) Space: O(1) (excluding output)