Two Out of Three
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.
nums1 = [1, 1, 3, 2], nums2 = [2, 3], nums3 = [3][2, 3]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;
}
Explanation
We want every value that shows up in at least two of the three arrays. The smart move is to ignore duplicates inside each array first, then just count how many arrays each value belongs to.
So we turn each array into a set: s1, s2, s3. A set automatically drops repeats, so a value counts at most once per array. That is exactly what we want, since a number appearing twice in nums1 should still only count as "one array".
Next we loop over the union s1 | s2 | s3 (every distinct value anywhere). For each value x we add up the memberships: (x in s1) + (x in s2) + (x in s3). In Python a true check counts as 1, so this sum is just "how many arrays contain x". If that sum is >= 2, we keep x.
Example: nums1 = [1, 1, 3, 2], nums2 = [2, 3], nums3 = [3]. The value 3 is in all three (sum 3), 2 is in two (sum 2), and 1 is in only one (sum 1). So the answer is [2, 3].
Because sets give instant membership checks, each value is handled in constant time and we only walk the combined values once.