2248. Intersection of Multiple Arrays LeetCode Solution
In this guide, you will get 2248. Intersection of Multiple Arrays LeetCode Solution with the best time and space complexity. The solution to Intersection of Multiple Arrays problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Intersection of Multiple Arrays solution in C++
- Intersection of Multiple Arrays solution in Java
- Intersection of Multiple Arrays solution in Python
- Additional Resources
Problem Statement of Intersection of Multiple Arrays
Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order.
Example 1:
Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]
Output: [3,4]
Explanation:
The only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4].
Example 2:
Input: nums = [[1,2,3],[4,5,6]]
Output: []
Explanation:
There does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].
Constraints:
1 <= nums.length <= 1000
1 <= sum(nums[i].length) <= 1000
1 <= nums[i][j] <= 1000
All the values of nums[i] are unique.
Complexity Analysis
- Time Complexity: O(\Sigma \texttt{nums[i]})
- Space Complexity: O(1001) = O(1)
2248. Intersection of Multiple Arrays LeetCode Solution in C++
class Solution {
public:
vector<int> intersection(vector<vector<int>>& nums) {
constexpr int kMax = 1000;
vector<int> ans;
vector<int> count(kMax + 1);
for (const vector<int>& row : nums)
for (const int a : row)
++count[a];
for (int i = 1; i <= kMax; ++i)
if (count[i] == nums.size())
ans.push_back(i);
return ans;
}
};
/* code provided by PROGIEZ */
2248. Intersection of Multiple Arrays LeetCode Solution in Java
class Solution {
public List<Integer> intersection(int[][] nums) {
final int kMax = 1000;
List<Integer> ans = new ArrayList<>();
int[] count = new int[kMax + 1];
for (int[] arr : nums)
for (final int a : arr)
++count[a];
for (int i = 1; i <= kMax; ++i)
if (count[i] == nums.length)
ans.add(i);
return ans;
}
}
// code provided by PROGIEZ
2248. Intersection of Multiple Arrays LeetCode Solution in Python
class Solution:
def intersection(self, nums: list[list[int]]) -> list[int]:
count = [0] * 1001
for row in nums:
for a in row:
count[a] += 1
return [i for i, c in enumerate(count)
if c == len(nums)]
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.