Hand of Straights

Medium

Problem

Return true if the cards can be split into groups of size groupSize, where each group is groupSize consecutive values.

Example 1

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

[1,2,3], [2,3,4], [6,7,8].

Example 2

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

Test cases

Case 1

Input:    [1,2,3,6,2,3,4,7,8], 3
Expected: true

Case 2

Input:    [1,2,3,4,5], 4
Expected: false

Case 3

Input:    [1,2], 1
Expected: true

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Smallest card starts a group

Time O(n log n)Space O(n)

The smallest remaining card must begin a run. Take it and the next groupSize − 1 values from the counts; fail if any is missing.

function isNStraightHand(hand, size) {
if (hand.length % size) return false;
const cnt = new Map();
for (const x of hand) cnt.set(x, (cnt.get(x) ?? 0) + 1);
for (const x of [...cnt.keys()].sort((a, b) => a - b)) {
const need = cnt.get(x);
if (!need) continue;
for (let v = x; v < x + size; v++) {
if ((cnt.get(v) ?? 0) < need) return false;
cnt.set(v, cnt.get(v) - need);
}
}
return true;
}