Hand of Straights

35 min · isNStraightHand()

A shuffled hand can hide several perfect runs — or one missing card that ruins all of them.

You're given an integer array hand and an integer groupSize. Decide whether every card can be rearranged into groups of exactly groupSize cards where each group contains consecutive values, meaning each value is exactly one greater than the previous one.

Return true when such a rearrangement exists and false otherwise. Every copy of a duplicate card is separate and must be used exactly once.

Constraints

  • 1 <= hand.length <= 10_000
  • 1 <= groupSize <= hand.length
  • 0 <= hand[i] <= 1_000_000_000

Hints

Check the card count first

Every group has the same size. If hand.length isn't divisible by groupSize, no rearrangement can use every card.

The smallest card has a forced role

Look at the smallest card that remains. Could it sit anywhere except at the beginning of a consecutive group?

Consume duplicates together

Count each value. If the smallest remaining value has k copies, you must start k groups there and remove k copies of every next value in those runs.

Follow-up

How would you return the actual groups while keeping O(n log n) time and O(n) extra space?

Visible cases

Examples

Example 1

ready
Input
hand = [
  1,
  2,
  3,
  6,
  2,
  3,
  4,
  7,
  8
]
groupSize = 3
Expected
true
Why
the cards form [1,2,3], [2,3,4], and [6,7,8]

Example 2

ready
Input
hand = [
  1,
  2,
  3,
  4,
  5
]
groupSize = 4
Expected
false
Why
five cards can't be divided into groups of four

Example 3

ready
Input
hand = [
  1,
  2,
  3,
  4,
  5,
  6
]
groupSize = 2
Expected
true
Why
three consecutive pairs use every card

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite