Python 0954.py
class Solution:
def canReorderDoubled(self, arr: List[int]) -> bool:
freq = defaultdict(int)
for a in arr:
freq[a] += 1
keys = sorted(freq, key = lambda x : abs(x))
for k in keys:
# map each number
freq[2 * k] -= freq[k]
if freq[2 * k] < 0:
return False
return True
Difficulty
and has an acceptance rate of about 40% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Hash Table
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation determines whether an integer array can be reordered so that for every element x there exists another element y such that y = 2 * x. The algorithm builds a frequency map of the values, processes the distinct numbers in order of increasing absolute magnitude, and attempts to pair each occurrence of a number with its double. If any required pairing cannot be satisfied, the function returns False; otherwise it returns True.
Key Steps
Building the frequency map
The first phase iterates over the input list and records how many times each integer appears.
freq = defaultdict(int)
for a in arr:
freq[a] += 1
The defaultdict automatically supplies a zero count for unseen keys, simplifying the increment operation.
Ordering the keys by absolute value
To guarantee that a smaller magnitude number is always paired before its potential double, the distinct keys are sorted based on their absolute values. This ordering is crucial for handling negative numbers and zero correctly.
keys = sorted(freq, key=lambda x: abs(x))
Pairing each number with its double
The core loop walks through the sorted keys. For each key k, the algorithm reduces the count of its double (2 * k) by the number of times k appears. If the resulting count for the double becomes negative, it indicates that there are not enough doubles to match all occurrences of k, and the function aborts with False.
for k in keys:
freq[2 * k] -= freq[k]
if freq[2 * k] < 0:
return False
If the loop completes without triggering the early return, every element has found a valid partner, and the function returns True.
return True
Edge Cases Handled
The algorithm gracefully manages several subtle scenarios:
-
Zero values: Since
0doubled is still0, the frequency of zero must be even. The sorted order processes zero like any other number; the subtractionfreq[0] -= freq[0]results in a zero count, and a negative count would only arise if the original count were odd, causing aFalsereturn. -
Negative numbers: By sorting on absolute value, a negative number such as
-3is processed before its double-6. This ensures that the required pairing direction is consistent regardless of sign. -
Mixed signs: When the array contains both positive and negative numbers, each sign group is handled independently because the absolute-value ordering separates them appropriately. For example,
-2is paired with-4without interference from2and4. -
Large magnitude gaps: If a number’s double does not exist in the original array, the subtraction will attempt to decrement a non-existent key, which
defaultdicttreats as zero. The resulting negative count triggers the earlyFalsereturn.
Performance Optimizations
The implementation incorporates several choices that keep the execution efficient:
-
Single pass frequency construction: Counting elements in one linear scan avoids repeated lookups or nested loops.
-
defaultdictfor on-the-fly keys: Accessing a missing key automatically yields a zero count, eliminating the need for explicit existence checks before subtraction. -
Sorting by absolute value only once: By generating a sorted list of distinct keys up front, the algorithm avoids repeated sorting or re-ordering during the pairing phase.
-
In-place frequency updates: Adjusting the counts directly in the
freqdictionary removes the overhead of auxiliary data structures and reduces memory churn. -
Early termination: As soon as an impossible pairing is detected (a negative count), the function returns immediately, preventing unnecessary processing of the remaining keys.
ELI5 - Simplified Explanation
Imagine you have a big bucket full of numbered building blocks. The goal is to see if every single block has a twin that is exactly twice its size living in the bucket with it. For example, if there is a number two, there must also be a number four. If there is a number five, there must be a ten.
The code starts by making a list of all the numbers in the bucket and counting how many times each one shows up. It keeps these counts in a special notebook so it knows exactly what information it has. After that, it sorts the keys in the notebook from the smallest absolute value to the largest. This way, the code looks at the smallest numbers first and works its way up.
For every number it checks, it looks for its double. When it finds the double, it takes one away from the count of that larger number to show that they have been paired up like best friends. If the code ever tries to find a double but discovers that none are left in the bucket, then it knows the pairing game cannot be finished. If it makes it through the entire list without running out of pairs, then it knows everyone found their special match.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | ||||
| LeetcodeHelp | C++ | Python | Java | |||||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| qiyuangong | Java | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| LeetcodeHelp | C++, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| qiyuangong | Java | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 2007: Find Original Array From Doubled Array
Solved On The Same Day
- problem 953: Verifying an Alien Dictionary
- problem 961: N-Repeated Element in Size 2N Array
- problem 2264: Largest 3-Same-Digit Number in String
- problem 2682: Find the Losers of the Circular Game
- problem 2784: Check if Array is Good
- problem 2848: Points That Intersect With Cars
- problem 2869: Minimum Operations to Collect Elements
- problem 890: Find and Replace Pattern
- problem 959: Regions Cut By Slashes
- problem 966: Vowel Spellchecker
- problem 1202: Smallest String With Swaps
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality