1. Brute Force

class Solution:
    def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
        def contains(arr, target):
            for num in arr:
                if num == target:
                    return True
            return False

        res = []
        for num in arr1:
            if contains(arr2, num) and contains(arr3, num):
                res.append(num)
        return res

Time & Space Complexity

  • Time complexity: O(n∗(m+k))O(n * (m + k))
  • Space complexity: O(1)O(1) extra space.

Where nn, mm, and kk are the lengths of the arrays arr1arr1, arr2arr2, and arr3arr3 respectively.


2. Hash Map

class Solution:
    def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
        count = {}
        for arr in (arr1, arr2, arr3):
            for num in arr:
                count[num] = count.get(num, 0) + 1

        res = []
        for num in arr1:
            if count[num] == 3:
                res.append(num)
        return res

Time & Space Complexity

  • Time complexity: O(n+m+k)O(n + m + k)
  • Space complexity: O(n+m+k)O(n + m + k)

Where nn, mm, and kk are the lengths of the arrays arr1arr1, arr2arr2, and arr3arr3 respectively.


class Solution:
    def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
        def binarySearch(arr, target):
            l, r = 0, len(arr) - 1
            while l <= r:
                mid = (l + r) // 2
                if arr[mid] == target:
                    return True
                if arr[mid] < target:
                    l = mid + 1
                else:
                    r = mid - 1
            return False

        res = []
        for num in arr1:
            if binarySearch(arr2, num) and binarySearch(arr3, num):
                res.append(num)
        return res

Time & Space Complexity

  • Time complexity: O(n∗(log⁡m+log⁡k))O(n * (\log m + \log k))
  • Space complexity: O(1)O(1) extra space.

Where nn, mm, and kk are the lengths of the arrays arr1arr1, arr2arr2, and arr3arr3 respectively.


4. Three Pointers

class Solution:
    def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
        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:
                mn = min(arr1[i], arr2[j], arr3[k])
                if arr1[i] == mn:
                    i += 1
                if arr2[j] == mn:
                    j += 1
                if arr3[k] == mn:
                    k += 1
        return res

Time & Space Complexity

  • Time complexity: O(n+m+k)O(n + m + k)
  • Space complexity: O(1)O(1) extra space.

Where nn, mm, and kk are the lengths of the arrays arr1arr1, arr2arr2, and arr3arr3 respectively.