Hand of Straights
Difficulty: Medium · Pattern: Greedy · LeetCode #846
Return true if the cards in hand can be rearranged into groups of groupSize consecutive values, with every card used exactly once.
Examples
text
hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 → true ([1,2,3],[2,3,4],[6,7,8])
hand = [1,2,3,4,5], groupSize = 4 → falseHints
- The smallest card in the hand can't be the middle or end of any group. It must start one.
- Count the cards. Repeatedly take the smallest remaining value
xand remove one each ofx, x+1, …, x+groupSize−1.
Approach
If len(hand) % groupSize != 0, return false. Count with a hash map, and walk the distinct values in sorted order. For each value x with c = cnt[x] > 0, start c groups at once: for k in 0..groupSize−1, require cnt[x+k] ≥ c, then subtract c.
The forced choice ("the smallest card must start a group") makes the greedy correct. O(n log n) for the sort. This is the same problem as LeetCode 1296 (Divide Array in Sets of K Consecutive Numbers).
Complexity
Time: O(n log n). Space: O(n).
Python solution
from collections import Counter
def isNStraightHand(hand, groupSize):
if len(hand) % groupSize:
return False
cnt = Counter(hand)
for x in sorted(cnt):
c = cnt[x]
if c:
for k in range(groupSize):
if cnt[x + k] < c:
return False
cnt[x + k] -= c
return TrueJavaScript solution
function isNStraightHand(hand, groupSize) {
if (hand.length % groupSize) 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 c = cnt.get(x);
if (!c) continue;
for (let k = 0; k < groupSize; k++) {
const have = cnt.get(x + k) || 0;
if (have < c) return false;
cnt.set(x + k, have - c);
}
}
return true;
}