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
18
class Solution {
 public:
  vector<int> intersection(vector<vector<int>>& nums) {
    constexpr int kMax = 1000;
    vector<int> ans;
    vector<int> count(kMax + 1);

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

    for (int i = 1; i <= kMax; ++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
17
class Solution {
  public List<Integer> intersection(int[][] nums) {
    final int MAX = 1000;
    List<Integer> ans = new ArrayList<>();
    int[] count = new int[MAX + 1];

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

    for (int i = 1; i <= MAX; ++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 row in nums:
      for a in row:
        count[a] += 1

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