520/670

520. Hand of Straights

Medium

Alice holds a hand of number cards, given as the integer array hand. She wants to lay the entire hand out as groups of exactly groupSize cards each, where every group is a run of consecutive values (for example [4, 5, 6] when groupSize = 3). Every card must land in exactly one group.

Given hand and the integer groupSize, return true if such a complete rearrangement exists and false otherwise.

Example 1:

Input: hand = [1, 2, 3, 6, 2, 3, 4, 7, 8], groupSize = 3

Output: true

Explanation: The nine cards split into the runs [1, 2, 3], [2, 3, 4] and [6, 7, 8].

Example 2:

Input: hand = [1, 2, 3, 4, 5], groupSize = 4

Output: false

Explanation: Five cards cannot be dealt into groups of four — the total count is not divisible by groupSize.

Constraints:

  • 1 ≤ hand.length ≤ 10⁴
  • 0 ≤ hand[i] ≤ 10⁹
  • 1 ≤ groupSize ≤ hand.length

Hints:

First check divisibility: if hand.length is not a multiple of groupSize, no arrangement can exist. Then think about the smallest card still in the hand — which group must it belong to?

The smallest remaining card can only ever be the *start* of a run (nothing smaller is left to precede it). So the greedy move is forced: take the minimum m and remove one copy each of m, m+1, …, m+groupSize−1, failing if any is missing. Count copies in a hash map and process distinct values in sorted order.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: hand = [1, 2, 3, 6, 2, 3, 4, 7, 8], groupSize = 3

Expected output: true