Two Out of Three

easy array hash table

Problem

Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values present in at least two of the three arrays.

Inputnums1 = [1, 1, 3, 2], nums2 = [2, 3], nums3 = [3]
Output[2, 3]
2 appears in nums1 and nums2; 3 appears in all three.

def two_out_of_three(nums1, nums2, nums3):
    s1, s2, s3 = set(nums1), set(nums2), set(nums3)
    res = []
    for x in s1 | s2 | s3:
        if (x in s1) + (x in s2) + (x in s3) >= 2:
            res.append(x)
    return res
function twoOutOfThree(nums1, nums2, nums3) {
  const s1 = new Set(nums1), s2 = new Set(nums2), s3 = new Set(nums3);
  const res = [];
  const all = new Set([...s1, ...s2, ...s3]);
  for (const x of all) {
    const c = (s1.has(x) ? 1 : 0) + (s2.has(x) ? 1 : 0) + (s3.has(x) ? 1 : 0);
    if (c >= 2) res.push(x);
  }
  return res;
}
class Solution {
    public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {
        Set<Integer> s1 = toSet(nums1), s2 = toSet(nums2), s3 = toSet(nums3);
        Set<Integer> all = new HashSet<>(); all.addAll(s1); all.addAll(s2); all.addAll(s3);
        List<Integer> res = new ArrayList<>();
        for (int x : all) {
            int c = (s1.contains(x) ? 1 : 0) + (s2.contains(x) ? 1 : 0) + (s3.contains(x) ? 1 : 0);
            if (c >= 2) res.add(x);
        }
        return res;
    }
    private Set<Integer> toSet(int[] a) { Set<Integer> s = new HashSet<>(); for (int v : a) s.add(v); return s; }
}
vector<int> twoOutOfThree(vector<int>& n1, vector<int>& n2, vector<int>& n3) {
    unordered_set<int> s1(n1.begin(), n1.end()), s2(n2.begin(), n2.end()), s3(n3.begin(), n3.end());
    unordered_set<int> all; all.insert(s1.begin(), s1.end()); all.insert(s2.begin(), s2.end()); all.insert(s3.begin(), s3.end());
    vector<int> res;
    for (int x : all) {
        int c = (s1.count(x) ? 1 : 0) + (s2.count(x) ? 1 : 0) + (s3.count(x) ? 1 : 0);
        if (c >= 2) res.push_back(x);
    }
    return res;
}
Time: O(n1 + n2 + n3) Space: O(n1 + n2 + n3)