Intersection of Multiple Arrays LeetCode solution in C++

1
class Solution {
2
public:
3
vector<int> intersection(vector<vector<int>> &nums) {
4
int n = nums.size(); // gives the no. of rows
5
map<int, int> mp; // we don't need unordered_map because we need the
6
// elements to be in sorted format.
7
vector<int> vec;
8

9
// traverse through the 2D array and store the frequency of each element
10
for (int row = 0; row < n; row++) {
11
for (int col = 0; col < nums[row].size(); col++) {
12
mp[nums[row][col]]++;
13
}
14
}
15

16
// In the 2D array, intersection occurs when the elements are present in
17
// every row. So the frequency of the element should match with the no. or
18
// rows in the 2D array.
19
for (auto element : mp)
20
if (element.second == n) vec.push_back(element.first);
21

22
// return the intersecting elements
23
return vec;
24
}
25
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0