Two Out of Three - Complete Solution Guide
Two Out of Three is LeetCode problem 2032, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 val
Detailed Explanation
The problem asks you to find all the unique numbers that appear in at least two out of three input integer arrays. The input consists of three arrays (`nums1`, `nums2`, `nums3`), and the output is a distinct array containing the numbers that meet the criteria. The order of numbers in the output array doesn't matter. The numbers in the input arrays are all positive integers within a specified range (1 to 100).
Solution Approach
The provided solutions use sets to efficiently solve the problem. Each input array is converted into a set. Then, the code iterates through each set and checks if elements of that set are present in at least one of the other sets. If a number is found in at least two sets, it's added to the result set. Finally, the result set is converted to a list (or vector) and returned.
Step-by-Step Algorithm
- Step 1: Convert each input array (`nums1`, `nums2`, `nums3`) into a set to eliminate duplicate numbers and enable efficient lookups.
- Step 2: Iterate through the elements of the first set (`s1`). For each element, check if it exists in either the second or third set. If it does, add it to a result set.
- Step 3: Repeat Step 2 for the elements of the second set (`s2`).
- Step 4: Repeat Step 2 for the elements of the third set (`s3`).
- Step 5: Convert the result set into a list (or array or vector) and return it.
Key Insights
- Insight 1: Using sets to efficiently check for the presence of a number in an array. Sets provide O(1) lookup time, improving the overall efficiency compared to linear search in arrays.
- Insight 2: Leveraging the properties of sets to automatically handle duplicates within each input array. Sets only store unique elements.
- Insight 3: The constraint that numbers are within the range 1-100 allows for alternative space-optimized solutions using a boolean array or a bit vector.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Topics
This problem involves: Array, Hash Table, Bit Manipulation.
Companies
Asked at: Booking.com, Info Edge.