Python 2206.py
class Solution:
def divideArray(self, nums: List[int]) -> bool:
freq = defaultdict(int)
for n in nums:
freq[n] += 1
return all((f & 1) == 0 for f in freq.values())
Difficulty
and has an acceptance rate of about 79% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Bit Manipulation
- Counting
- Hash Table
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 defines a class Solution with a single method divideArray. The method receives a list of integers and determines whether the list can be partitioned into pairs such that each pair contains equal values. The core idea is to count the occurrences of each distinct integer and then verify that every count is an even number. If all counts are even, the method returns True; otherwise it returns False.
Key Steps
The first important step is the construction of a frequency map. A defaultdict with integer default values is used so that each new key is automatically initialized to zero. The loop iterates over the input list and increments the count for each element.
freq = defaultdict(int)
for n in nums:
freq[n] += 1
After the frequency map is populated, the method evaluates whether every frequency value satisfies the even-ness condition. This is performed with a generator expression passed to the built-in all function. The expression uses a bitwise AND with 1 to test the least-significant bit; a result of 0 indicates an even number.
return all((f & 1) == 0 for f in freq.values())
The combination of these two steps yields a concise solution that directly reflects the problem’s requirement.
Edge Cases Handled
The algorithm naturally accommodates several edge conditions without additional code. When the input list is empty, the frequency map remains empty, and freq.values() yields an empty iterator. The all function applied to an empty iterable returns True, which correctly reflects that an empty list can be considered trivially partitionable into zero pairs.
If the list contains a single distinct value repeated an odd number of times, the frequency map will hold a single entry with an odd count. The bitwise check (f & 1) == 0 will evaluate to False, causing all to return False. This correctly signals that an odd count cannot be fully paired.
When the list includes many distinct values, each with its own count, the generator expression evaluates each count independently. Any occurrence of an odd count immediately forces the overall result to False, while the presence of only even counts yields True. This behavior ensures that mixed distributions are handled correctly.
Performance Optimizations
The implementation leverages a defaultdict to avoid explicit existence checks when updating frequencies. This reduces the overhead of conditional logic inside the counting loop, allowing each iteration to consist of a single dictionary lookup and increment operation.
The use of a generator expression inside all provides short-circuit evaluation. As soon as an odd frequency is encountered, the generator stops producing further values, and all returns False immediately. This prevents unnecessary examination of the remaining frequencies, which can be beneficial when the input list is large and an odd count appears early.
The bitwise operation (f & 1) == 0 is a low-cost way to test evenness compared to modulo division. Bitwise checks are generally faster because they operate directly on the binary representation of the integer, avoiding the more expensive division operation.
Overall, the code achieves a linear pass over the input list to build the frequency map and a second linear pass over the distinct keys to verify evenness, with early exit possible during the verification phase. This design balances clarity with efficient use of Python’s built-in constructs.
ELI5 - Simplified Explanation
Imagine you have a big pile of colorful building blocks and you want to put them into pairs so every block has a matching partner. This code starts by grabbing a little notebook to keep track of how many blocks of each color are in the pile. It goes through every block one by one and writes down the count for each color in that notebook. Once the notebook is finished, the code checks every single color to see if there is an even number of blocks. If every color has a pair where no block is left lonely, then the mission is a success. If even one color has an odd number of blocks, it means one block would be left without a friend, so the answer is no.
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 | Java | C++ | Python | TS | ||||||
| WalkCCC | Java | C++ | Python | ||||||||
| leetcode.ca | Java | C++ | Python | JS | Go | Rust | TS | ||||
| Progiez | Java | C++ | Python | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| Dijkstra-Edu | Java | ||||||||||
| DimitrisJim | Go | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| lkwq007 | Python | ||||||||||
| Shamik07 | Dart | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| Dijkstra-Edu | Java | ||||||||||
| DimitrisJim | Go | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lkwq007 | Python | ||||||||||
| Shamik07 | Dart | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 1636: Sort Array by Increasing Frequency
- problem 3069: Distribute Elements Into Two Arrays I
- problem 3072: Distribute Elements Into Two Arrays II
Solved On The Same Day
- problem 2200: Find All K-Distant Indices in an Array
- problem 2210: Count Hills and Valleys in an Array
- problem 2224: Minimum Number of Operations to Convert Time
- problem 2165: Smallest Value of the Rearranged Number
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