loading

Hand of Straights — Step-by-Step Visualization

mediumLeetCode #846ArrayHash TableGreedySorting

Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size `groupSize`, and consists of `groupSize` consecutive cards. Given an integer array `hand` where `hand[i]` is the value written on the `i`th card and an integer `groupSize`, return `true` if she can rearrange the cards, or `false` otherwise.

Algorithm Pattern

Greedy with Sorted Frequency Map

Key Idea

Always start a new group from the smallest available card. If you can't form a consecutive group of size groupSize starting from that card, it's impossible.

Step-by-Step Approach

  1. If len(hand) % groupSize != 0, return False.
  2. Count card frequencies with a hash map.
  3. Sort the unique cards.
  4. For each smallest card with count > 0, try to decrement the next groupSize consecutive cards.
  5. If any card is missing (count = 0), return False.
  6. Return True.

Common Gotchas

  • Must start from the smallest card each iteration — greedy order matters.
  • Use an ordered structure to always find the smallest available card.

Related Problems