#2956
Find Common Elements Between Two Arrays
EasyArrayHash TableHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(n + m) |
💡
Intuition
Time O(n + m)Space O(n + m)
Using a HashSet allows us to quickly check for the existence of elements, reducing the time complexity significantly. This is like having a quick reference guide that tells you if an item is present without having to search through a list.
⚙️
Algorithm
6 steps- 1Step 1: Create a HashSet from nums2 for fast look-up.
- 2Step 2: Initialize counters answer1 and answer2 to 0.
- 3Step 3: For each element in nums1, check if it exists in the HashSet. If it does, increment answer1.
- 4Step 4: Create a HashSet from nums1 for the second check.
- 5Step 5: For each element in nums2, check if it exists in the second HashSet. If it does, increment answer2.
- 6Step 6: Return [answer1, answer2].
solution.py8 lines
1# Full working Python code
2
3def find_common_elements(nums1, nums2):
4 set_nums2 = set(nums2)
5 answer1 = sum(1 for num in nums1 if num in set_nums2)
6 set_nums1 = set(nums1)
7 answer2 = sum(1 for num in nums2 if num in set_nums1)
8 return [answer1, answer2]ℹ
Complexity note: The time complexity is O(n + m) because we create sets from both arrays and then check membership, which is efficient. The space complexity is O(n + m) due to the storage of two sets.
- 1Using a HashSet allows for faster lookups compared to nested loops.
- 2Understanding the trade-off between time and space complexity is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.