#2206
Divide Array Into Equal Pairs
EasyArrayHash TableBit ManipulationCountingHash 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)
The optimal solution leverages counting the occurrences of each number. If every number appears an even number of times, we can form pairs. This is efficient and straightforward.
⚙️
Algorithm
3 steps- 1Step 1: Create a frequency count of each number in the array.
- 2Step 2: Iterate through the frequency count and check if each count is even.
- 3Step 3: If all counts are even, return true; otherwise, return false.
solution.py9 lines
1# Full working Python code
2
3def can_form_pairs(nums):
4 from collections import Counter
5 count = Counter(nums)
6 for freq in count.values():
7 if freq % 2 != 0:
8 return False
9 return Trueℹ
Complexity note: This complexity is linear because we only traverse the array a couple of times: once for counting and once for checking counts.
- 1Counting occurrences allows for a quick check on pairing feasibility.
- 2Even counts are essential for forming pairs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.