Two Out of Three

We have three integer arrays, and we want to find all the unique values that are present in at least two out of the three arrays.

Here’s a simple approach:

Steps

  1. Create three sets, one for each array, containing the unique elements of the respective array.
  2. Create a dictionary to keep track of the occurrence count for each unique value across the three sets.
  3. Iterate through the three sets, incrementing the count for each unique value in the dictionary.
  4. Iterate through the dictionary, and if the count for any value is greater than or equal to 2, add it to the result list.
  5. Return the result list containing the distinct values that are present in at least two out of the three arrays.

Code

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
        # Step 1: Create sets for the unique elements in each array
        set1 = set(nums1)
        set2 = set(nums2)
        set3 = set(nums3)

        # Step 2: Initialize a dictionary to keep track of the occurrence count
        count_dict = {}

        # Step 3: Iterate through the sets, incrementing the count for each unique value
        for num_set in [set1, set2, set3]:
            for num in num_set:
                count_dict[num] = count_dict.get(num, 0) + 1

        # Step 4: Create a result list and add values with count >= 2
        result = []
        for num, count in count_dict.items():
            if count >= 2:
                result.append(num)

        # Step 5: Return the result list
        return result

Explanation

The code takes advantage of sets and dictionaries to efficiently find the unique values that are present in at least two arrays. By keeping track of the occurrence count in a dictionary, we can quickly identify which values meet the criteria. The use of sets ensures that we only consider the distinct values in each array, and the final result list will also contain only distinct values.