#954
Array of Doubled Pairs
MediumArrayHash TableGreedySortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution involves using a hash map to count occurrences of each number and then checking if we can form pairs of numbers and their doubles. This is efficient and avoids the need for generating permutations.
⚙️
Algorithm
4 steps- 1Step 1: Count the occurrences of each number in a hash map.
- 2Step 2: Sort the unique numbers in the hash map.
- 3Step 3: For each number, check if the double exists in the hash map and if there are enough occurrences to form pairs.
- 4Step 4: If all numbers can be paired successfully, return true; otherwise, return false.
solution.py10 lines
1# Full working Python code
2from collections import Counter
3
4def canReorderDoubled(arr):
5 count = Counter(arr)
6 for x in sorted(count.keys()):
7 if count[x] > count[2 * x]:
8 return False
9 count[2 * x] -= count[x]
10 return Trueℹ
Complexity note: The time complexity is O(n log n) due to sorting the unique keys of the hash map, while the space complexity is O(n) for storing the counts.
- 1The problem requires pairing numbers with their doubles, which can be efficiently managed using counting.
- 2Sorting the unique numbers helps ensure that we handle smaller numbers first, which is crucial for pairing.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.