Problem 954

Abstract / Summary

Check if array can be split into groups of four with equal values where one is double the other.

Note

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

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
14 lines | 390 bytes | submitted December 4, 2023 | GitHub   9% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 40% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Hash Table
  • Sorting
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 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 0 doubled is still 0, the frequency of zero must be even. The sorted order processes zero like any other number; the subtraction freq[0] -= freq[0] results in a zero count, and a negative count would only arise if the original count were odd, causing a False return.

  • Negative numbers: By sorting on absolute value, a negative number such as -3 is 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, -2 is paired with -4 without interference from 2 and 4.

  • 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 defaultdict treats as zero. The resulting negative count triggers the early False return.

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.

  • defaultdict for 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 freq dictionary 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.

written by openai gpt

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.

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 = 7 | μ = 6.96 | σ = 1.32

Complexity Analysis

Time: loglinear
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 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++
28 links | 16 authors | 7 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

12 solutions   December 4, 2023

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