🧠
Hash Map Frequency Counting
💡 This approach uses a hash map to count frequencies, which is a common and efficient technique to handle duplicates and membership checks.
Intuition
Count the frequency of each element in one array, then iterate over the second array to find common elements by checking and decrementing counts.
Algorithm
- Create a hash map to store frequencies of elements in nums1.
- Iterate over nums1 and increment counts in the hash map.
- Initialize an empty list for the intersection.
- Iterate over nums2, and for each element, check if it exists in the hash map with count > 0.
- If yes, append the element to the intersection and decrement its count in the hash map.
- Return the intersection list.
💡 Using a hash map avoids nested loops and efficiently tracks how many times each element can be matched.
def intersect(nums1, nums2):
counts = {}
for num in nums1:
counts[num] = counts.get(num, 0) + 1
intersection = []
for num in nums2:
if counts.get(num, 0) > 0:
intersection.append(num)
counts[num] -= 1
return intersection
# Driver code
if __name__ == '__main__':
print(intersect([1,2,2,1], [2,2])) # Output: [2, 2]
Line Notes
counts = {}Initialize dictionary to count frequencies
for num in nums1:Count each element's frequency in nums1
counts[num] = counts.get(num, 0) + 1Increment count or initialize to 1
intersection = []Prepare list to store intersection
for num in nums2:Check each element in nums2 against counts
if counts.get(num, 0) > 0:Only add if element is still available
intersection.append(num)Add matched element
counts[num] -= 1Decrement count to avoid overcounting
import java.util.*;
public class Solution {
public static int[] intersect(int[] nums1, int[] nums2) {
Map<Integer, Integer> counts = new HashMap<>();
for (int num : nums1) counts.put(num, counts.getOrDefault(num, 0) + 1);
List<Integer> intersection = new ArrayList<>();
for (int num : nums2) {
if (counts.getOrDefault(num, 0) > 0) {
intersection.add(num);
counts.put(num, counts.get(num) - 1);
}
}
int[] result = new int[intersection.size()];
for (int i = 0; i < intersection.size(); i++) result[i] = intersection.get(i);
return result;
}
public static void main(String[] args) {
int[] res = intersect(new int[]{1,2,2,1}, new int[]{2,2});
System.out.println(Arrays.toString(res)); // Output: [2, 2]
}
}
Line Notes
Map<Integer, Integer> counts = new HashMap<>();Create map to count frequencies
for (int num : nums1) counts.put(num, counts.getOrDefault(num, 0) + 1);Count frequencies in nums1
List<Integer> intersection = new ArrayList<>();List to store intersection
if (counts.getOrDefault(num, 0) > 0) {Check if element available to match
intersection.add(num);Add matched element
counts.put(num, counts.get(num) - 1);Decrement count to avoid duplicates
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> counts;
for (int num : nums1) counts[num]++;
vector<int> intersection;
for (int num : nums2) {
if (counts[num] > 0) {
intersection.push_back(num);
counts[num]--;
}
}
return intersection;
}
int main() {
vector<int> nums1 = {1,2,2,1};
vector<int> nums2 = {2,2};
vector<int> res = intersect(nums1, nums2);
for (int num : res) cout << num << ' '; // Output: 2 2
cout << endl;
return 0;
}
Line Notes
unordered_map<int, int> counts;Hash map to store frequencies
for (int num : nums1) counts[num]++;Count frequencies in nums1
vector<int> intersection;Vector to store intersection
if (counts[num] > 0) {Check if element available to match
intersection.push_back(num);Add matched element
counts[num]--;Decrement count to avoid duplicates
function intersect(nums1, nums2) {
const counts = new Map();
for (const num of nums1) {
counts.set(num, (counts.get(num) || 0) + 1);
}
const intersection = [];
for (const num of nums2) {
if ((counts.get(num) || 0) > 0) {
intersection.push(num);
counts.set(num, counts.get(num) - 1);
}
}
return intersection;
}
// Test
console.log(intersect([1,2,2,1], [2,2])); // Output: [2, 2]
Line Notes
const counts = new Map();Initialize map to count frequencies
for (const num of nums1) {Count frequencies in nums1
counts.set(num, (counts.get(num) || 0) + 1);Increment count or initialize to 1
const intersection = [];Array to store intersection
if ((counts.get(num) || 0) > 0) {Check if element available to match
intersection.push(num);Add matched element
counts.set(num, counts.get(num) - 1);Decrement count to avoid duplicates
TimeO(m + n)
SpaceO(min(m, n))
Counting frequencies takes O(m), iterating nums2 takes O(n). Space depends on smaller array for frequency map.
💡 For arrays of size 100, this means about 200 operations, much faster than brute force.
Interview Verdict: Accepted / Optimal for most cases
This approach is efficient and commonly accepted in interviews.