#2032

Two Out of Three

Easy
ArrayHash TableBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a HashMap allows us to count occurrences of each number across the three arrays efficiently. This way, we can determine which numbers appear in at least two arrays in a single pass.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a HashMap to count occurrences of each number.
  2. 2Step 2: Iterate through each array and update the count in the HashMap.
  3. 3Step 3: Create a result list to store numbers that appear at least twice.
  4. 4Step 4: Iterate through the HashMap and add keys with a count of 2 or more to the result list.
  5. 5Step 5: Return the result list.
solution.py10 lines
1def twoOutOfThree(nums1, nums2, nums3):
2    from collections import defaultdict
3    count = defaultdict(int)
4    for num in nums1:
5        count[num] += 1
6    for num in nums2:
7        count[num] += 1
8    for num in nums3:
9        count[num] += 1
10    return [num for num, cnt in count.items() if cnt > 1]

Complexity note: The time complexity is O(n) because we make a single pass through each of the three arrays to count occurrences. The space complexity is O(n) due to the HashMap storing counts of potentially all unique elements.

  • 1Using a HashMap allows for efficient counting of occurrences across multiple arrays.
  • 2Understanding how to leverage data structures can significantly improve performance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.