Skip to content

2032. Two Out of Three 👍

  • Time: $O(n)$
  • Space: $O(100) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  vector<int> twoOutOfThree(vector<int>& nums1, vector<int>& nums2,
                            vector<int>& nums3) {
    vector<int> ans;
    vector<int> count(101);

    for (const vector<int>& nums : {nums1, nums2, nums3})
      update(count, nums);

    for (int i = 1; i <= 100; ++i)
      if (count[i] >= 2)
        ans.push_back(i);

    return ans;
  }

 private:
  void update(vector<int>& count, const vector<int>& nums) {
    for (const int num : unordered_set<int>(nums.begin(), nums.end()))
      ++count[num];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {
    List<Integer> ans = new ArrayList<>();
    int[] count = new int[101];

    for (int[] nums : new int[][] {nums1, nums2, nums3})
      update(count, nums);

    for (int i = 1; i <= 100; ++i)
      if (count[i] >= 2)
        ans.add(i);

    return ans;
  }

  private void update(int[] count, int[] nums) {
    for (final int num : Arrays.stream(nums).boxed().collect(Collectors.toSet()))
      ++count[num];
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def twoOutOfThree(
      self,
      nums1: list[int],
      nums2: list[int],
      nums3: list[int],
  ) -> list[int]:
    count = collections.Counter()
    for nums in nums1, nums2, nums3:
      count.update(set(nums))
    return [i for i, c in count.items() if c >= 2]