Two Out of Three Problem
#2032
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2032.
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.
Example 1:
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:
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:
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 <= 1001 <= nums1[i], nums2[j], nums3[k] <= 100
Solution
Approach: Counting by value
Every value is between 1 and 100, so we can record, for each array, which values it contains. Then we go through the values 1 to 100 and keep a value when it appears in at least two of the three arrays.
The time complexity is O(n_1 + n_2 + n_3 + C) and the space complexity is O(C), where n_1, n_2, n_3 are the lengths of the arrays and C = 100 is the range of the values.
class Solution:
def twoOutOfThree(
self, nums1: List[int], nums2: List[int], nums3: List[int]
) -> List[int]:
s1, s2, s3 = set(nums1), set(nums2), set(nums3)
return [i for i in range(1, 101) if (i in s1) + (i in s2) + (i in s3) > 1]