Problem 846

Abstract / Summary

Given a hand of integers and a group size, check if the hand can be rearranged into groups of consecutive numbers of that size.

Note

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

Python 0846.py

class Solution:
    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
        if len(hand) % groupSize != 0:
            return False

        # card counter ...
        freq = defaultdict(int)
        for h in hand:
            freq[h] += 1

        for f in sorted(freq):
            # already processed
            if freq[f] == 0:
                continue

            # start a new group
            step = freq[f] # maybe multiple groups with the same cards
            for i in range(groupSize):
                freq[f + i] -= step
                # not consecutive ?
                if freq[f + i] < 0:
                    return False

        return True
24 lines | 707 bytes | submitted October 25, 2023 | GitHub   31% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 58% (800k+ 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 a multiset of integers can be partitioned into groups of a fixed size such that each group consists of consecutive numbers. It follows a deterministic, greedy strategy that builds groups starting from the smallest available card and consumes the required consecutive cards in bulk. The algorithm returns True only when every card can be placed into a valid group; otherwise it returns False.

Validation

The first logical gate checks whether the total number of cards can possibly be divided into groups of the requested size. If the remainder of the division is non-zero, the function immediately rejects the input.

if len(hand) % groupSize != 0:
    return False

This guard eliminates impossible cases without further processing.

Frequency Counting

A frequency map records how many times each distinct card appears. The use of defaultdict(int) ensures that missing keys default to zero, allowing straightforward increment operations.

freq = defaultdict(int)
for h in hand:
    freq[h] += 1

The map serves as the central data structure for tracking remaining cards as groups are formed.

Group Formation

The core loop iterates over the keys of the frequency map in ascending order. Processing in sorted order guarantees that groups always start from the smallest still-available card, which is essential for maintaining consecutiveness.

for f in sorted(freq):
    if freq[f] == 0:
        continue
    step = freq[f]
    for i in range(groupSize):
        freq[f + i] -= step
        if freq[f + i] < 0:
            return False
  • The if freq[f] == 0 check skips values that have already been exhausted by earlier groups.
  • step = freq[f] captures the number of groups that must start at the current card value; this handles cases where multiple identical cards initiate parallel groups.
  • The inner loop decrements the count for each consecutive card required by the groups. If any count drops below zero, it indicates a missing or insufficient card, and the function aborts with False.

If the outer loop completes without triggering a negative count, every card has been successfully allocated, and the function returns True.

Edge Cases Handled

The algorithm gracefully manages several subtle scenarios:

  • When the hand contains duplicate values, step may be greater than one, causing multiple groups to be launched simultaneously from the same starting card.
  • If a required consecutive card is absent, the subtraction yields a negative frequency, causing an immediate failure.
  • Situations where a later card appears in excess but earlier cards are missing are caught because the algorithm always begins groups from the smallest remaining card.
  • Hands whose length is not a multiple of groupSize are rejected upfront, preventing unnecessary work.

Performance Optimizations

The implementation incorporates a few deliberate choices that reduce overhead:

  • Using a defaultdict eliminates the need for explicit existence checks when populating the frequency map.
  • Sorting the distinct card values once (sorted(freq)) provides ordered traversal without repeated sorting operations.
  • The early-exit condition inside the inner loop (if freq[f + i] < 0) stops processing at the first sign of impossibility, avoiding needless iteration over the remaining cards.
  • By processing groups in bulk (step = freq[f]) the algorithm reduces the number of inner-loop executions compared to handling each group individually.

These design decisions collectively keep the runtime proportional to the number of distinct cards plus the total number of cards needed for group formation, while maintaining a compact memory footprint centered on the frequency map.

written by openai gpt

ELI5 - Simplified Explanation

Think of this code like sorting a big pile of playing cards into small sets. Each set needs to have consecutive numbers, like a three, a four, and a five.

First, the code checks if the total number of cards can be split evenly into groups of the right size. If there are leftovers, it knows right away that the game cannot be played.

Next, it makes a list to remember how many of each card number exists in the pile. It counts them up to see exactly what is available.

Then, the code starts looking through the numbers starting from the smallest one. It picks up the smallest card and creates a new group by looking for the next few cards in line. If it needs a four to follow a three, but there is no four in the pile, it knows the cards cannot fit together properly. It keeps doing this for every card until the whole pile is organized or it runs out of cards that fit the pattern. If it manages to use every card to make these perfect groups, the job is finished.

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.67 | σ = 1.02

Complexity Analysis

not analyzed yet

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 TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
bujosa Python
charles-wangkai Java
fengvyi C++
halfrost Go
JoshCrozier JS
lkwq007 Python
MacJim C++
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
bujosa Python
charles-wangkai Java
fengvyi C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
MacJim C++
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
zfang399 C++
33 links | 20 authors | 8 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

2 easy 2 medium
5 solutions   October 25, 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