InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Greedy

Hand of Straights

medium Original ↗ 00:00

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 = 3True — split into [1,2,3], [2,3,4], [6,7,8].
  • hand = [1,2,3,4,5], groupSize = 4False5 is not divisible by 4, so equal-sized groups are impossible.
  • hand = [8,10,12], groupSize = 3False — 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug