Skip to content

2248. Intersection of Multiple Arrays 👍

  • Time: $O(\Sigma \texttt{nums[i]})$
  • Space: $O(1001) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  vector<int> intersection(vector<vector<int>>& nums) {
    vector<int> ans;
    vector<int> count(1001);

    for (const vector<int>& A : nums)
      for (const int a : A)
        ++count[a];

    for (int i = 1; i < 1001; ++i)
      if (count[i] == nums.size())
        ans.push_back(i);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public List<Integer> intersection(int[][] nums) {
    List<Integer> ans = new ArrayList<>();
    int[] count = new int[1001];

    for (int[] A : nums)
      for (final int a : A)
        ++count[a];

    for (int i = 1; i < 1001; ++i)
      if (count[i] == nums.length)
        ans.add(i);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def intersection(self, nums: list[list[int]]) -> list[int]:
    count = [0] * 1001

    for A in nums:
      for a in A:
        count[a] += 1

    return [i for i, c in enumerate(count)
            if c == len(nums)]