Leetcode 2032. Two Out of Three
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.
Map
(specifically a HashMap
) to count the occurrences of each number across the three sets.import java.util.*;
public class Solution {
public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {
// Create sets to remove duplicates within the same array
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
Set<Integer> set3 = new HashSet<>();
for (int num : nums1) set1.add(num);
for (int num : nums2) set2.add(num);
for (int num : nums3) set3.add(num);
// Use a map to count occurrences across sets
Map<Integer, Integer> countMap = new HashMap<>();
// Helper method to count occurrences
addToMap(set1, countMap);
addToMap(set2, countMap);
addToMap(set3, countMap);
// Prepare the result list
List<Integer> result = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
if (entry.getValue() >= 2) {
result.add(entry.getKey());
}
}
return result;
}
private void addToMap(Set<Integer> set, Map<Integer, Integer> map) {
for (int num : set) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
}
}
n
, m
, and p
are the sizes of nums1
, nums2
, and nums3
respectively.Adding to Map: O( | set1 | + | set2 | + | set3 | ) where | set1 | , | set2 | , and | set3 | are the sizes of the sets created from the arrays. |
k
is the number of unique elements found across all sets (bounded by the sum of the lengths of the input arrays).Overall, the time complexity is O(n + m + p), which is linear with respect to the total number of elements in the input arrays.
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?