Problem 2206

Abstract / Summary

Check if the array length is even and all elements can be paired so each pair has the same sum.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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())
6 lines | 210 bytes | submitted February 10, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 79% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Counting
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.93 | σ = 1.36

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
28 links | 15 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

5 solutions   February 10, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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