LeetCode 2248: Intersection of Multiple Arrays
Problem Description
Explanation
To find the intersection of multiple arrays, we can iterate through all the arrays and keep track of the common elements among them. We can use a set to store the elements of the first array and then iterate through the rest of the arrays to find the common elements. If an element is present in all arrays, we add it to the result set.
Algorithm
- Create a set to store the elements of the first array.
- Iterate through the rest of the arrays.
- For each array, iterate through its elements.
- If an element is present in the set, add it to a temporary set.
- Replace the original set with the temporary set after processing each array.
- Convert the final set to a list and return it.
Time Complexity
Let n be the total number of elements in all arrays and k be the number of arrays. The time complexity of this algorithm is O(n) since we iterate through all elements once.
Space Complexity
The space complexity is O(n) as we store the elements in sets and lists.
Solutions
class Solution {
public List<Integer> intersectionOfArrays(int[][] nums) {
Set<Integer> common = new HashSet<>();
for (int num : nums[0]) {
common.add(num);
}
for (int i = 1; i < nums.length; i++) {
Set<Integer> temp = new HashSet<>();
for (int num : nums[i]) {
if (common.contains(num)) {
temp.add(num);
}
}
common = temp;
}
List<Integer> result = new ArrayList<>(common);
Collections.sort(result);
return result;
}
}
Loading editor...