846. Hand of Straights
Medium NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Greedy
- Time
- O(n log n)
- Space
- O(n)
Standard Solution (C++)
SummaryDetermine if a hand of cards can be rearranged into groups of consecutive values, each group of a given size.
Approach
Key idea: Greedily build groups starting from the smallest available card; each smallest card must begin a run of consecutive values.
Steps:
- If the total count is not divisible by groupSize, return false.
- Count occurrences in an ordered map.
- Repeatedly take the smallest card with positive count and consume groupSize consecutive values starting there, decrementing counts.
- If any required consecutive value is missing, return false.
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int groupSize) {
if (hand.size() % groupSize != 0) return false;
map<int,int> count;
for (int c : hand) count[c]++;
while (!count.empty()) {
int start = count.begin()->first;
for (int v = start; v < start + groupSize; ++v) {
auto it = count.find(v);
if (it == count.end()) return false;
if (--(it->second) == 0) count.erase(it);
}
}
return true;
}
}; Time O(n log n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.