InterviewPrepKit

Home / Coding / Greedy

Hand of Straights

medium Original β†—
Solving tips
  • Recognize this as a greedy grouping problem: the smallest remaining value has no freedom and must start its own run of groupSize consecutive cards.
  • Early-reject when len(hand) % groupSize != 0, then use a Counter plus a min-heap (or sorted distinct keys) to always fetch the current smallest value.
  • When consuming a run, if any needed value's count hits zero but it isn't the current minimum, fail now β€” a later group could never obtain it.
  • Target O(n log n) time and O(n) space; the common pitfall is peeking the min without verifying counts stay in sync as you decrement.

Problem

You are given an integer array hand (a hand of cards, each an integer value) and an integer groupSize. Determine whether the cards can be rearranged into groups such that every group has exactly groupSize cards and the values within each group are consecutive integers (e.g. [4,5,6] for groupSize = 3).

Return True if such a partition of all the cards exists, otherwise False. Every card must be used exactly once.

(This is identical to LeetCode’s β€œDivide Array in Sets of K Consecutive Numbers.”)

Examples

  • hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 β†’ True β€” split into [1,2,3], [2,3,4], [6,7,8].
  • hand = [1,2,3,4,5], groupSize = 4 β†’ False β€” 5 is not divisible by 4, so equal-sized groups are impossible.
  • hand = [8,10,12], groupSize = 3 β†’ False β€” the values are not consecutive, so no run of 3 can be formed.

Constraints

  • 1 <= len(hand) <= 10^4
  • 0 <= hand[i] <= 10^9
  • 1 <= groupSize <= len(hand)

Values can be huge, so index-by-value arrays are out; a hash count keyed on value is the right structure.

Think about it first

Hint 1 A quick reject: if len(hand) is not divisible by groupSize, the answer is immediately False.
Hint 2 Consider the smallest remaining card value. It cannot sit in the middle or end of any run β€” nothing smaller exists to precede it. So what group is it forced to begin?
Hint 3 The smallest value x must start a group [x, x+1, ..., x+groupSize-1]. Consume one of each; if any is missing, fail. Repeat with the new smallest. A min-heap or sorted counter of distinct values drives this.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.