Problem 525857 · medium · Phase 05 Advanced Algorithms & Graphs

Deal the Cards Into Straight Runs

greedy · hash map · sorting

You hold cards with integer values cards. Decide whether all of them can be dealt into groups of exactly w cards where each group is a run of w consecutive values (for example 4, 5, 6 when w = 3). Every card must be used exactly once. Return True or False.

Examples

Input:  cards = [3, 1, 2, 5, 4, 6], w = 3
Output: True
Explanation: [1, 2, 3] and [4, 5, 6].
Input:  cards = [1, 1, 2, 3, 3, 4], w = 3
Output: False
Explanation: The run starting at 1 uses the only 2, so the second 1 cannot start a run.

Constraints

  • 0 <= len(cards) <= 10**5, 1 <= w <= 1000, -10**9 <= cards[i] <= 10**9.
  • An empty hand is True.
  • Target complexity: O(n log n + n * w) in the worst case, near O(n log n) in practice.

Goals

  • Argue that the smallest remaining card must start a run
  • Consume whole runs at once using counts instead of single cards
  • Detect impossible splits early
Starting Python…