Skip to content
Problem 846 · LeetCode 846(opens in a new tab)

Hand of Straights

MediumGreedy

You hold some playing cards, and hand[i] is the number on card i. You want to split all of them into groups of exactly groupSize cards, where each group is a run of consecutive numbers such as 4, 5, 6.

Return true if every card can be placed in such a group, and false if not.

Example 1

Input:  hand = [5, 7, 6, 6, 8, 7], groupSize = 3
Output: true
Why:    [5, 6, 7] and [6, 7, 8]
2 more examples and the constraints

Example 2

Input:  hand = [10, 11, 13, 12, 14], groupSize = 2
Output: false
Why:    5 cards cannot split into pairs

Example 3

Input:  hand = [4, 4, 5, 6], groupSize = 2
Output: false
Why:    both 4s start a pair, but there is only one 5

Constraints

  • 1 ≤ number of cards ≤ 10,000
  • 0 ≤ number on a card ≤ 1,000,000,000
  • 1 ≤ groupSize ≤ number of cards

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort and remove runsO(n²)
  2. Count map, greedyO(n log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 cardsVerdict
Sort and remove runsO(n²)
Right idea, slow removals
Count map, greedyO(n log n)
Best; one sort, one sweep

n = number of cards.

Edge cases to test

  • Cards do not divide evenly. 5 cards with groupSize 2 is false before any other work.
  • groupSize = 1. Every card is a run of one, so the answer is always true.
  • Duplicates. [0, 0] with groupSize 2 is false: two equal cards are not consecutive.
  • Large values. Numbers go up to 1,000,000,000, so use a map, not an array indexed by value.

Common mistakes

  • Starting runs from any card instead of the smallest one left, which can strand cards.
  • Using an array indexed by card value, which is far too big for values up to a billion.
  • Forgetting to skip values whose count has already dropped to 0.

How to talk through it

  1. 1Clarify. Must every card be used? Can values repeat? How large can a value be?
  2. 2Find the forced move. The smallest card left has nothing below it, so it must start a run. That makes a greedy choice safe.
  3. 3Give the simple version. Sort and remove runs from a list; say the removals make it O(n²).
  4. 4Code the count map. Count copies, walk values in order, and take need copies from each value in the run at once.
  5. 5Test out loud. Run an uneven card count, groupSize 1 and [4, 4, 5, 6] before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?