#350
Intersection of Two Arrays II
EasyArrayHash TableTwo PointersBinary SearchSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a HashMap allows us to count the occurrences of each number in one array and then find the intersection efficiently. This reduces the number of checks needed.
⚙️
Algorithm
3 steps- 1Step 1: Create a HashMap to count occurrences of each number in nums1.
- 2Step 2: Iterate through nums2, checking if the number exists in the HashMap.
- 3Step 3: If it exists, add it to the result and decrement the count in the HashMap.
solution.py10 lines
1from collections import Counter
2
3def intersect(nums1, nums2):
4 counts = Counter(nums1)
5 result = []
6 for num in nums2:
7 if counts[num] > 0:
8 result.append(num)
9 counts[num] -= 1
10 return resultℹ
Complexity note: The time complexity is O(n) because we traverse both arrays once, and the space complexity is O(n) due to the HashMap storing counts.
- 1Using a HashMap can significantly reduce the time complexity.
- 2Understanding how to manage counts of elements is crucial for intersection problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.