Problem

Given three integer arrays nums1, nums2, and nums3, return adistinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order.

Examples

Example 1

1
2
3
4
5
Input: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]
Output: [3,2]
Explanation: The values that are present in at least two arrays are:
- 3, in all three arrays.
- 2, in nums1 and nums2.

Example 2

1
2
3
4
5
6
Input: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]
Output: [2,3,1]
Explanation: The values that are present in at least two arrays are:
- 2, in nums2 and nums3.
- 3, in nums1 and nums2.
- 1, in nums1 and nums3.

Example 3

1
2
3
Input: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]
Output: []
Explanation: No value is present in at least two arrays.

Constraints

  • 1 <= nums1.length, nums2.length, nums3.length <= 100
  • 1 <= nums1[i], nums2[j], nums3[k] <= 100

Solution

Method 1 – Hash Set and Counting

Intuition

Count how many arrays each value appears in using sets and a counter.

Approach

  1. For each array, create a set of its elements.
  2. For each value in the union of all sets, count in how many sets it appears.
  3. Return values that appear in at least two sets.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import java.util.*;
class Solution {
    public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {
        Set<Integer> s1 = new HashSet<>(), s2 = new HashSet<>(), s3 = new HashSet<>();
        for (int x : nums1) s1.add(x);
        for (int x : nums2) s2.add(x);
        for (int x : nums3) s3.add(x);
        List<Integer> res = new ArrayList<>();
        for (int x = 1; x <= 100; ++x) {
            int cnt = 0;
            if (s1.contains(x)) cnt++;
            if (s2.contains(x)) cnt++;
            if (s3.contains(x)) cnt++;
            if (cnt >= 2) res.add(x);
        }
        return res;
    }
}
1
2
3
def twoOutOfThree(nums1, nums2, nums3):
    s1, s2, s3 = set(nums1), set(nums2), set(nums3)
    return [x for x in range(1, 101) if (x in s1) + (x in s2) + (x in s3) >= 2]

Complexity

  • ⏰ Time complexity: O(1) — Only 100 possible values.
  • 🧺 Space complexity: O(1) — For sets of size at most 100.