Two Out of Three - Problem

Given three integer arrays nums1, nums2, and nums3, return a distinct 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.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]
Output: [2,3]
💡 Note: Value 2 appears in nums1 and nums2. Value 3 appears in all three arrays. Value 1 only appears in nums1.
Example 2 — No Overlap
$ Input: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]
Output: [1,2,3]
💡 Note: Value 1 appears in nums1 and nums3. Value 2 appears in nums2 and nums3. Value 3 appears in nums1 and nums2.
Example 3 — Single Array Only
$ Input: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]
Output: []
💡 Note: No value appears in at least two arrays, so the result is empty.

Constraints

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

Visualization

Tap to expand
Two Out of Three INPUT nums1: 1 1 3 2 nums2: 2 3 nums3: 3 Convert to Sets: set1 = {1, 3, 2} set2 = {2, 3} set3 = {3} ALGORITHM STEPS 1 Create Sets Remove duplicates from each array using sets 2 Count Occurrences Track how many sets contain each number Value | Sets Count 1 | 1 2 | 2 OK 3 | 3 OK 3 Filter Results Keep values with count >= 2 FINAL RESULT set1 set2 set3 2 3 Output Array: 2 3 Values in 2+ arrays [2, 3] Key Insight: Convert each array to a Set to remove duplicates, then count how many sets contain each value. Time Complexity: O(n1 + n2 + n3) | Space Complexity: O(n1 + n2 + n3) for storing unique elements. TutorialsPoint - Two Out of Three | Optimal Solution (HashSet Counting)
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
23.0K Views
Medium Frequency
~15 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen