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 result in any order.
from collections import defaultdict
def twoOutOfThree(nums1, nums2, nums3):
# Convert each list to a set to remove duplicates
set1, set2, set3 = set(nums1), set(nums2), set(nums3)
# Dictionary to keep track of the appearance count
appearance_count = defaultdict(int)
# Function to update the count dictionary
def update_count(num_set):
for num in num_set:
appearance_count[num] += 1
update_count(set1)
update_count(set2)
update_count(set3)
# Collect numbers that appear in at least two sets
result = [num for num, count in appearance_count.items() if count > 1]
return result
# Example usage:
nums1 = [1, 1, 3, 2]
nums2 = [2, 3]
nums3 = [3]
print(twoOutOfThree(nums1, nums2, nums3)) # Output: [2, 3]
n
into a set takes O(n). Since we have three lists, this step takes O(n + m + o) where n
, m
, and o
are lengths of nums1
, nums2
, and nums3
respectively.n + m + o
entries, thus taking O(n + m + o).Overall, the time complexity is O(n + m + o), which is efficient for this problem.
The space complexity is mainly from:
So, the space complexity is O(n + m + o).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?