15% off all plans & roadmaps Use code

See plans

Hand of Straights

Updated

TL;DR: Decide whether a hand of cards splits into groups of groupSize consecutive values. Count each value, then always start groups at the smallest remaining card, because that card cannot go anywhere else.

Problem

You are given an integer array hand, where each element is the value of one card, and an integer groupSize, the number of cards every group must hold. Split all the cards into groups of exactly groupSize cards.

A group is valid only if its values are consecutive integers with no gaps. Equal values are separate cards, so duplicates can land in different groups. Return true if the whole hand can be split this way, otherwise return false. Card order in hand does not matter, and every card belongs to exactly one group.

Example 1

Input: hand = [11,12,13,21,22,23], groupSize = 3
Output: true
Explanation: The cards split into [11, 12, 13] and [21, 22, 23].

Example 2

Input: hand = [14,15,17,18,19,20], groupSize = 3
Output: false
Explanation: The hand has six cards, but a group starting at 14 needs 14, 15, 16, and no 16 exists.

Example 3

Input: hand = [20,21,22,23,21,22,23,24], groupSize = 4
Output: true
Explanation: One valid split is [20, 21, 22, 23] and [21, 22, 23, 24].

Constraints

  • 1 <= hand.length <= 10^4
  • 0 <= hand[i] <= 10^9
  • 1 <= groupSize <= hand.length
  • All values in hand are integers

Constraints that matter

  • hand.length is at most 10^4, so an O(n^2) scan is about 10^8 steps in the worst case. It passes, but O(n log n) is the safer target.
  • hand[i] goes up to 10^9, so you cannot use an array indexed by card value. Use a hash map or a sorted map keyed by value.
  • groupSize is at least 1 and at most hand.length. When groupSize is 1, every hand works, and the same code handles it without a special case.
  • Every card must be used. If hand.length % groupSize != 0, return false right away, before any counting.

View on LeetCode

Hints

Hint 1

This is a greedy problem over sorted values.

Hint 2

Sort the cards.

Solution

Intuition

This is a greedy problem over sorted values. Look at the smallest card that is still unused. Nothing smaller remains, so a group holding that card cannot extend downward. That card must be the lowest card of its group.

Picture a row of labeled mailboxes, one per card value, each holding a stack of letters for that value. The lowest non-empty mailbox must start a route, so you take one letter from each of the next groupSize boxes, and the mailbox letter counts are the hash map entries.

That observation removes every choice. The group that contains the smallest card is fully determined: it is the value, the value plus 1, and so on up to the value plus groupSize - 1. If any of those is missing, no valid split exists. If they are all present, taking them cannot hurt, because every valid split must contain exactly that group.

Duplicates make it faster to work with counts than with single cards. If the smallest value x appears k times, all k copies must start groups. So you remove k copies of each value in the window from x to x + groupSize - 1 in one move.

Look for a partition into runs of consecutive values with no freedom in how to start. Whenever the lowest remaining item has a forced role, sort and process from the bottom.

Watch the pattern animation

Worked example

Input: hand = [11, 12, 13, 21, 22, 23], groupSize = 3
Output: true
Explanation: The six cards split into the runs [11, 12, 13] and [21, 22, 23]. Each run has three consecutive values, and no card is left over.

Approach 1: Brute force: sort and scan for each group

Sort the cards. Then build one group at a time. Pick the first unused card, mark it used, and scan forward through the array to find an unused card equal to the next needed value. Repeat until the group has groupSize cards or the scan runs out.

This follows the greedy rule, but it does no counting. Every group start walks the array again, and used cards are skipped one by one.

Steps

  1. If n % groupSize != 0, return false.
  2. Copy and sort the cards. Create a used array of n flags, all false.
  3. For each index i in order, skip it if it is used.
  4. Mark i used, set need = cards[i] + 1, and set taken = 1.
  5. Scan j from i + 1 while taken < groupSize. When cards[j] is unused and equals need, mark it used, increase need, and increase taken.
  6. If the scan ends with taken < groupSize, return false.
  7. After all indices are handled, return true.

Dry run

Sorted cards: [11, 12, 13, 21, 22, 23], groupSize 3. Six is divisible by 3.

  • i = 0: card 11 starts a group. The scan finds 12 at j = 1 and 13 at j = 2. taken = 3, group done.
  • i = 1, i = 2: both used, skip.
  • i = 3: card 21 starts a group. The scan finds 22 at j = 4 and 23 at j = 5. Group done.
  • i = 4, i = 5: used, skip.

No group failed, so the answer is true.

Complexity

TimeO(n^2)
SpaceO(n)

Let n be the number of cards. There are n / groupSize group starts, and each start scans at most n positions, so the work is O(n * n / groupSize), which is O(n^2) when groupSize is small. The sorted copy and the used array each hold n items, giving O(n) space. Sorting adds O(n log n), which the scans dominate.

PythonTested in our runner

from typing import List

class Solution:
    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
        n = len(hand)
        if n % groupSize != 0:
            return False
        cards = sorted(hand)
        used = [False] * n
        for i in range(n):
            if used[i]:
                continue
            used[i] = True
            need = cards[i] + 1
            taken = 1
            j = i + 1
            while j < n and taken < groupSize:
                if not used[j] and cards[j] == need:
                    used[j] = True
                    need += 1
                    taken += 1
                j += 1
            if taken < groupSize:
                return False
        return True
Sorting Based pattern infographic for Hand of Straights

Solution pattern

Sorting Based

Part of Greedy Patterns

Approach 2: Sorted frequency map, greedy by windowOptimalSorting Based

What's slow in the brute force: each group start rescans the array and steps over used cards, and equal cards are handled one at a time. Duplicates cause the same scan to repeat for every copy.

The insight that fixes it: store a count per distinct value and handle all copies of a value together. Visit the distinct values in increasing order. If value x still has k copies, then k groups must start at x.

Check that each of x through x + groupSize - 1 has at least k copies, and subtract k from each. Lookups are O(1) with a hash map, so the scan is gone.

Steps

  1. If n % groupSize != 0, return false.
  2. Build a map from each card value to its count.
  3. Sort the distinct values, or use a sorted map.
  4. For each value x in increasing order, let groups = count[x]. Skip it if groups is 0.
  5. For each card from x to x + groupSize - 1, return false if count[card] < groups.
  6. Otherwise subtract groups from count[card].
  7. If every value is processed without failure, return true.

Dry run

Example: hand = [11, 12, 13, 21, 22, 23], groupSize = 3. Six cards, divisible by 3. The counts are {11:1, 12:1, 13:1, 21:1, 22:1, 23:1}.

StepCurrent value xgroupsWindow checkedCounts after
111111, 12, 13 all have at least 1{11:0, 12:0, 13:0, 21:1, 22:1, 23:1}
2120skippedunchanged
3130skippedunchanged
421121, 22, 23 all have at least 1all counts 0
5220skippedunchanged
6230skippedunchanged

No window failed, so the result is true.

On example 2, [14, 15, 17, 18, 19, 20], the first window starts at 14 and needs 16. Its count is 0, which is less than 1, so the result is false.

Complexity

TimeO(n log n)
SpaceO(n)

Let n be the number of cards and u the number of distinct values, so u <= n. Counting costs O(n) and sorting the distinct values costs O(u log u), which is O(n log n). A window of groupSize cards is processed only for a value with a positive count, and each such window removes at least groupSize cards from the hand.

So at most n / groupSize windows run before success or the first failure, and their total work is O(n). The map holds at most u entries, so space is O(n).

PythonTested in our runner

from typing import List
from collections import Counter

class Solution:
    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
        if len(hand) % groupSize != 0:
            return False
        counts = Counter(hand)
        for value in sorted(counts):
            groups = counts[value]
            if groups == 0:
                continue
            for card in range(value, value + groupSize):
                if counts.get(card, 0) < groups:
                    return False
                counts[card] -= groups
        return True

Common mistakes

  • Skipping the n % groupSize check. A hand like [1, 2, 3, 4] with groupSize = 3 might look fine at first, but the last card has no group. Return false before counting.
  • Subtracting 1 from each window value instead of groups. If count[x] is 2, two groups start at x, so subtract groups from every value in the window.
  • Reading counts[card] on a plain dict or map for a missing key. In Python a plain dict raises, and in C++ counts[card] inserts a zero entry while you iterate. Use get or find and treat a missing value as 0.
  • Processing values in hash order instead of sorted order. Starting at a larger value can let a smaller value be consumed as a middle card, which gives wrong answers. Sort the distinct values first.
  • Forgetting to skip values whose count is already 0. With groups = 0 the window check passes, but a missing neighbour could still trigger a false return False when have < 0 is never true. Skipping keeps the logic clear and avoids needless work.
  • Writing if counts[card] <= groups or checking only == groups. A neighbour with more copies than groups is fine, because the extra copies start later groups. The condition to reject is count < groups.

Edge cases

  • groupSize = 1: every hand works, since each card is its own group. The result is true.
  • hand.length not divisible by groupSize, for example [1, 2, 3, 4] with groupSize = 3: return false immediately.
  • One group using every card, for example [5, 6, 7] with groupSize = 3: return true.
  • Cards with a gap, as in [14, 15, 17, 18, 19, 20] with groupSize = 3: return false at the window starting at 14.
  • Heavy duplicates, as in [1, 1, 2, 2, 3, 3] with groupSize = 3: two groups start at 1, so subtract 2 from each of 1, 2, 3 and return true.
  • Large values, as in [1000000000, 999999999] with groupSize = 2: return true. The window math stays within a 32-bit int here, since value + groupSize is at most 10^9 + 10^4.

Follow-ups interviewers ask

What if the cards arrive one at a time and you cannot sort them up front?
Keep a sorted structure such as a balanced tree map of counts, or a min-heap of distinct values plus a hash map of counts. Each time you need the smallest remaining value, read it from the structure, then apply the same window subtraction. The cost is O(log n) per insertion or lookup of the minimum.
Can you avoid subtracting in a window and still be O(n log n)?
Yes. Walk the sorted distinct values and track how many groups are still open. At value x, compare count[x] with the number of groups that started at x - 1 and are still running. If count[x] is smaller than the open groups, return false. Groups that started groupSize values ago close, and any extra copies open new groups. This uses a queue of start counts and touches each value once.
What changes if a group may have any groupSize distinct values, not consecutive ones?
The sorted order no longer forces anything. You only need every value count to be at most n / groupSize and n % groupSize == 0, because you can deal the cards out in sorted rotation. Consecutive values are what make the smallest card a forced start.

Hand of Straights FAQ

What is the time complexity of Hand of Straights?

The sorted frequency solution runs in O(n log n), where n is the number of cards. Counting is O(n), sorting the distinct values is O(u log u) with u <= n, and the window subtractions total O(n). The brute force scan is O(n^2).

Why use a sorted frequency map for Hand of Straights?

The smallest remaining card must start a group, so you need to find it fast and handle all its copies at once. Counts let you subtract a whole batch of groups in one pass, and sorted order tells you which value to start from. Together they remove the repeated scanning.

Can Hand of Straights be solved in O(1) extra space?

Not in a way that keeps O(n log n) time in general. You need to track how many copies of each value remain, which takes O(u) space. You could sort in place and mark used cards, but the scan for the next value then costs more time. The standard trade is O(n) space for O(n log n) time.

How do I solve LeetCode 846 in Python?

Return False if len(hand) % groupSize is nonzero. Build a Counter, loop over sorted(counts), and for each value with groups copies subtract groups from every value in the window value to value + groupSize - 1. Return False if any window value has fewer than groups copies, otherwise return True.

Why is the greedy choice correct in Hand of Straights?

The smallest remaining value x has nothing below it, so every copy of x is the lowest card of its group. That fixes k groups, each needing x through x + groupSize - 1. Any valid split contains exactly these cards, so taking them first never loses a solution.

Does the same idea solve LeetCode 1296?

Yes. Divide Array in Sets of K Consecutive Numbers asks the same question with k in place of groupSize. The same sorted count and window subtraction works unchanged.

Asked at

See which companies ask this — Pro

Practise it