15% off all plans & roadmaps Use code
See plansHand of Straights
- LeetCode 846
- Medium
- Greedy Patterns
- Sorting Based
Updated
TL;DR: Decide whether a hand of cards splits into groups of groupSize consecutive values. Count each value, then always start groups at the smallest remaining card, because that card cannot go anywhere else.
Problem
You are given an integer array hand, where each element is the value of one card, and an integer groupSize, the number of cards every group must hold. Split all the cards into groups of exactly groupSize cards.
A group is valid only if its values are consecutive integers with no gaps. Equal values are separate cards, so duplicates can land in different groups. Return true if the whole hand can be split this way, otherwise return false. Card order in hand does not matter, and every card belongs to exactly one group.
Example 1
Input: hand = [11,12,13,21,22,23], groupSize = 3 Output: true Explanation: The cards split into [11, 12, 13] and [21, 22, 23].
Example 2
Input: hand = [14,15,17,18,19,20], groupSize = 3 Output: false Explanation: The hand has six cards, but a group starting at 14 needs 14, 15, 16, and no 16 exists.
Example 3
Input: hand = [20,21,22,23,21,22,23,24], groupSize = 4 Output: true Explanation: One valid split is [20, 21, 22, 23] and [21, 22, 23, 24].
Constraints
1 <= hand.length <= 10^40 <= hand[i] <= 10^91 <= groupSize <= hand.length- All values in
handare integers
Constraints that matter
hand.lengthis at most 10^4, so an O(n^2) scan is about 10^8 steps in the worst case. It passes, but O(n log n) is the safer target.hand[i]goes up to 10^9, so you cannot use an array indexed by card value. Use a hash map or a sorted map keyed by value.groupSizeis at least 1 and at mosthand.length. WhengroupSizeis 1, every hand works, and the same code handles it without a special case.- Every card must be used. If
hand.length % groupSize != 0, returnfalseright away, before any counting.
Hints
Hint 1
This is a greedy problem over sorted values.
Hint 2
Sort the cards.
Solution
Intuition
This is a greedy problem over sorted values. Look at the smallest card that is still unused. Nothing smaller remains, so a group holding that card cannot extend downward. That card must be the lowest card of its group.
Picture a row of labeled mailboxes, one per card value, each holding a stack of letters for that value. The lowest non-empty mailbox must start a route, so you take one letter from each of the next groupSize boxes, and the mailbox letter counts are the hash map entries.
That observation removes every choice. The group that contains the smallest card is fully determined: it is the value, the value plus 1, and so on up to the value plus groupSize - 1. If any of those is missing, no valid split exists. If they are all present, taking them cannot hurt, because every valid split must contain exactly that group.
Duplicates make it faster to work with counts than with single cards. If the smallest value x appears k times, all k copies must start groups. So you remove k copies of each value in the window from x to x + groupSize - 1 in one move.
Look for a partition into runs of consecutive values with no freedom in how to start. Whenever the lowest remaining item has a forced role, sort and process from the bottom.
Worked example
Input: hand = [11, 12, 13, 21, 22, 23], groupSize = 3 Output: true Explanation: The six cards split into the runs [11, 12, 13] and [21, 22, 23]. Each run has three consecutive values, and no card is left over.
Approach 1: Brute force: sort and scan for each group
Sort the cards. Then build one group at a time. Pick the first unused card, mark it used, and scan forward through the array to find an unused card equal to the next needed value. Repeat until the group has groupSize cards or the scan runs out.
This follows the greedy rule, but it does no counting. Every group start walks the array again, and used cards are skipped one by one.
Steps
- If
n % groupSize != 0, returnfalse. - Copy and sort the cards. Create a
usedarray ofnflags, all false. - For each index
iin order, skip it if it is used. - Mark
iused, setneed = cards[i] + 1, and settaken = 1. - Scan
jfromi + 1whiletaken < groupSize. Whencards[j]is unused and equalsneed, mark it used, increaseneed, and increasetaken. - If the scan ends with
taken < groupSize, returnfalse. - After all indices are handled, return
true.
Dry run
Sorted cards: [11, 12, 13, 21, 22, 23], groupSize 3. Six is divisible by 3.
i = 0: card 11 starts a group. The scan finds 12 atj = 1and 13 atj = 2.taken = 3, group done.i = 1,i = 2: both used, skip.i = 3: card 21 starts a group. The scan finds 22 atj = 4and 23 atj = 5. Group done.i = 4,i = 5: used, skip.
No group failed, so the answer is true.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(n) |
Let n be the number of cards. There are n / groupSize group starts, and each start scans at most n positions, so the work is O(n * n / groupSize), which is O(n^2) when groupSize is small. The sorted copy and the used array each hold n items, giving O(n) space. Sorting adds O(n log n), which the scans dominate.
PythonTested in our runner
from typing import List
class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
n = len(hand)
if n % groupSize != 0:
return False
cards = sorted(hand)
used = [False] * n
for i in range(n):
if used[i]:
continue
used[i] = True
need = cards[i] + 1
taken = 1
j = i + 1
while j < n and taken < groupSize:
if not used[j] and cards[j] == need:
used[j] = True
need += 1
taken += 1
j += 1
if taken < groupSize:
return False
return True
JavaTested in our runner
import java.util.*;
class Solution {
public boolean isNStraightHand(int[] hand, int groupSize) {
int n = hand.length;
if (n % groupSize != 0) {
return false;
}
int[] cards = hand.clone();
Arrays.sort(cards);
boolean[] used = new boolean[n];
for (int i = 0; i < n; i++) {
if (used[i]) {
continue;
}
used[i] = true;
int need = cards[i] + 1;
int taken = 1;
for (int j = i + 1; j < n && taken < groupSize; j++) {
if (!used[j] && cards[j] == need) {
used[j] = true;
need++;
taken++;
}
}
if (taken < groupSize) {
return false;
}
}
return true;
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int groupSize) {
int n = hand.size();
if (n % groupSize != 0) {
return false;
}
vector<int> cards(hand);
sort(cards.begin(), cards.end());
vector<bool> used(n, false);
for (int i = 0; i < n; i++) {
if (used[i]) {
continue;
}
used[i] = true;
int need = cards[i] + 1;
int taken = 1;
for (int j = i + 1; j < n && taken < groupSize; j++) {
if (!used[j] && cards[j] == need) {
used[j] = true;
need++;
taken++;
}
}
if (taken < groupSize) {
return false;
}
}
return true;
}
};
JavaScriptTested in our runner
/**
* @param {number[]} hand
* @param {number} groupSize
* @return {boolean}
*/
var isNStraightHand = function(hand, groupSize) {
const n = hand.length;
if (n % groupSize !== 0) {
return false;
}
const cards = [...hand].sort((a, b) => a - b);
const used = new Array(n).fill(false);
for (let i = 0; i < n; i++) {
if (used[i]) {
continue;
}
used[i] = true;
let need = cards[i] + 1;
let taken = 1;
for (let j = i + 1; j < n && taken < groupSize; j++) {
if (!used[j] && cards[j] === need) {
used[j] = true;
need++;
taken++;
}
}
if (taken < groupSize) {
return false;
}
}
return true;
};
GoTested in our runner
import "sort"
func isNStraightHand(hand []int, groupSize int) bool {
n := len(hand)
if n%groupSize != 0 {
return false
}
cards := make([]int, n)
copy(cards, hand)
sort.Ints(cards)
used := make([]bool, n)
for i := 0; i < n; i++ {
if used[i] {
continue
}
used[i] = true
need := cards[i] + 1
taken := 1
for j := i + 1; j < n && taken < groupSize; j++ {
if !used[j] && cards[j] == need {
used[j] = true
need++
taken++
}
}
if taken < groupSize {
return false
}
}
return true
}
C#Tested in our runner
public class Solution {
public bool isNStraightHand(int[] hand, int groupSize) {
int n = hand.Length;
if (n % groupSize != 0) {
return false;
}
int[] cards = (int[])hand.Clone();
System.Array.Sort(cards);
bool[] used = new bool[n];
for (int i = 0; i < n; i++) {
if (used[i]) {
continue;
}
used[i] = true;
int need = cards[i] + 1;
int taken = 1;
for (int j = i + 1; j < n && taken < groupSize; j++) {
if (!used[j] && cards[j] == need) {
used[j] = true;
need++;
taken++;
}
}
if (taken < groupSize) {
return false;
}
}
return true;
}
}

Solution pattern
Sorting Based
Part of Greedy Patterns
Approach 2: Sorted frequency map, greedy by windowOptimalSorting Based
What's slow in the brute force: each group start rescans the array and steps over used cards, and equal cards are handled one at a time. Duplicates cause the same scan to repeat for every copy.
The insight that fixes it: store a count per distinct value and handle all copies of a value together. Visit the distinct values in increasing order. If value x still has k copies, then k groups must start at x.
Check that each of x through x + groupSize - 1 has at least k copies, and subtract k from each. Lookups are O(1) with a hash map, so the scan is gone.
Steps
- If
n % groupSize != 0, returnfalse. - Build a map from each card value to its count.
- Sort the distinct values, or use a sorted map.
- For each value
xin increasing order, letgroups = count[x]. Skip it ifgroupsis 0. - For each
cardfromxtox + groupSize - 1, returnfalseifcount[card] < groups. - Otherwise subtract
groupsfromcount[card]. - If every value is processed without failure, return
true.
Dry run
Example: hand = [11, 12, 13, 21, 22, 23], groupSize = 3. Six cards, divisible by 3. The counts are {11:1, 12:1, 13:1, 21:1, 22:1, 23:1}.
| Step | Current value x | groups | Window checked | Counts after |
|---|---|---|---|---|
| 1 | 11 | 1 | 11, 12, 13 all have at least 1 | {11:0, 12:0, 13:0, 21:1, 22:1, 23:1} |
| 2 | 12 | 0 | skipped | unchanged |
| 3 | 13 | 0 | skipped | unchanged |
| 4 | 21 | 1 | 21, 22, 23 all have at least 1 | all counts 0 |
| 5 | 22 | 0 | skipped | unchanged |
| 6 | 23 | 0 | skipped | unchanged |
No window failed, so the result is true.
On example 2, [14, 15, 17, 18, 19, 20], the first window starts at 14 and needs 16. Its count is 0, which is less than 1, so the result is false.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(n) |
Let n be the number of cards and u the number of distinct values, so u <= n. Counting costs O(n) and sorting the distinct values costs O(u log u), which is O(n log n). A window of groupSize cards is processed only for a value with a positive count, and each such window removes at least groupSize cards from the hand.
So at most n / groupSize windows run before success or the first failure, and their total work is O(n). The map holds at most u entries, so space is O(n).
PythonTested in our runner
from typing import List
from collections import Counter
class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize != 0:
return False
counts = Counter(hand)
for value in sorted(counts):
groups = counts[value]
if groups == 0:
continue
for card in range(value, value + groupSize):
if counts.get(card, 0) < groups:
return False
counts[card] -= groups
return True
JavaTested in our runner
import java.util.*;
class Solution {
public boolean isNStraightHand(int[] hand, int groupSize) {
if (hand.length % groupSize != 0) {
return false;
}
TreeMap<Integer, Integer> counts = new TreeMap<>();
for (int card : hand) {
counts.merge(card, 1, Integer::sum);
}
List<Integer> values = new ArrayList<>(counts.keySet());
for (int value : values) {
int groups = counts.get(value);
if (groups == 0) {
continue;
}
for (int card = value; card < value + groupSize; card++) {
int have = counts.getOrDefault(card, 0);
if (have < groups) {
return false;
}
counts.put(card, have - groups);
}
}
return true;
}
}
C++Tested in our runner
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int groupSize) {
if (hand.size() % groupSize != 0) {
return false;
}
map<int, int> counts;
for (int card : hand) {
counts[card]++;
}
for (auto& entry : counts) {
int groups = entry.second;
if (groups == 0) {
continue;
}
for (int card = entry.first; card < entry.first + groupSize; card++) {
auto it = counts.find(card);
if (it == counts.end() || it->second < groups) {
return false;
}
it->second -= groups;
}
}
return true;
}
};
JavaScriptTested in our runner
/**
* @param {number[]} hand
* @param {number} groupSize
* @return {boolean}
*/
var isNStraightHand = function(hand, groupSize) {
if (hand.length % groupSize !== 0) {
return false;
}
const counts = new Map();
for (const card of hand) {
counts.set(card, (counts.get(card) || 0) + 1);
}
const values = [...counts.keys()].sort((a, b) => a - b);
for (const value of values) {
const groups = counts.get(value);
if (groups === 0) {
continue;
}
for (let card = value; card < value + groupSize; card++) {
const have = counts.get(card) || 0;
if (have < groups) {
return false;
}
counts.set(card, have - groups);
}
}
return true;
};
GoTested in our runner
import "sort"
func isNStraightHand(hand []int, groupSize int) bool {
if len(hand)%groupSize != 0 {
return false
}
counts := make(map[int]int)
for _, card := range hand {
counts[card]++
}
values := make([]int, 0, len(counts))
for v := range counts {
values = append(values, v)
}
sort.Ints(values)
for _, value := range values {
groups := counts[value]
if groups == 0 {
continue
}
for card := value; card < value+groupSize; card++ {
if counts[card] < groups {
return false
}
counts[card] -= groups
}
}
return true
}
C#Tested in our runner
public class Solution {
public bool isNStraightHand(int[] hand, int groupSize) {
if (hand.Length % groupSize != 0) {
return false;
}
var counts = new Dictionary<int, int>();
foreach (int card in hand) {
counts[card] = counts.GetValueOrDefault(card, 0) + 1;
}
var values = counts.Keys.OrderBy(v => v).ToList();
foreach (int value in values) {
int groups = counts[value];
if (groups == 0) {
continue;
}
for (int card = value; card < value + groupSize; card++) {
int have = counts.GetValueOrDefault(card, 0);
if (have < groups) {
return false;
}
counts[card] = have - groups;
}
}
return true;
}
}
Common mistakes
- Skipping the
n % groupSizecheck. A hand like [1, 2, 3, 4] withgroupSize = 3might look fine at first, but the last card has no group. Returnfalsebefore counting. - Subtracting 1 from each window value instead of
groups. Ifcount[x]is 2, two groups start atx, so subtractgroupsfrom every value in the window. - Reading
counts[card]on a plain dict or map for a missing key. In Python a plain dict raises, and in C++counts[card]inserts a zero entry while you iterate. Usegetorfindand treat a missing value as 0. - Processing values in hash order instead of sorted order. Starting at a larger value can let a smaller value be consumed as a middle card, which gives wrong answers. Sort the distinct values first.
- Forgetting to skip values whose count is already 0. With
groups = 0the window check passes, but a missing neighbour could still trigger a falsereturn Falsewhenhave < 0is never true. Skipping keeps the logic clear and avoids needless work. - Writing
if counts[card] <= groupsor checking only== groups. A neighbour with more copies thangroupsis fine, because the extra copies start later groups. The condition to reject iscount < groups.
Edge cases
groupSize = 1: every hand works, since each card is its own group. The result istrue.hand.lengthnot divisible bygroupSize, for example [1, 2, 3, 4] withgroupSize = 3: returnfalseimmediately.- One group using every card, for example [5, 6, 7] with
groupSize = 3: returntrue. - Cards with a gap, as in [14, 15, 17, 18, 19, 20] with
groupSize = 3: returnfalseat the window starting at 14. - Heavy duplicates, as in [1, 1, 2, 2, 3, 3] with
groupSize = 3: two groups start at 1, so subtract 2 from each of 1, 2, 3 and returntrue. - Large values, as in [1000000000, 999999999] with
groupSize = 2: returntrue. The window math stays within a 32-bit int here, sincevalue + groupSizeis at most 10^9 + 10^4.
Follow-ups interviewers ask
- What if the cards arrive one at a time and you cannot sort them up front?
- Keep a sorted structure such as a balanced tree map of counts, or a min-heap of distinct values plus a hash map of counts. Each time you need the smallest remaining value, read it from the structure, then apply the same window subtraction. The cost is O(log n) per insertion or lookup of the minimum.
- Can you avoid subtracting in a window and still be O(n log n)?
- Yes. Walk the sorted distinct values and track how many groups are still open. At value
x, comparecount[x]with the number of groups that started atx - 1and are still running. Ifcount[x]is smaller than the open groups, return false. Groups that startedgroupSizevalues ago close, and any extra copies open new groups. This uses a queue of start counts and touches each value once. - What changes if a group may have any
groupSizedistinct values, not consecutive ones? - The sorted order no longer forces anything. You only need every value count to be at most
n / groupSizeandn % groupSize == 0, because you can deal the cards out in sorted rotation. Consecutive values are what make the smallest card a forced start.
Hand of Straights FAQ
What is the time complexity of Hand of Straights?
The sorted frequency solution runs in O(n log n), where n is the number of cards. Counting is O(n), sorting the distinct values is O(u log u) with u <= n, and the window subtractions total O(n). The brute force scan is O(n^2).
Why use a sorted frequency map for Hand of Straights?
The smallest remaining card must start a group, so you need to find it fast and handle all its copies at once. Counts let you subtract a whole batch of groups in one pass, and sorted order tells you which value to start from. Together they remove the repeated scanning.
Can Hand of Straights be solved in O(1) extra space?
Not in a way that keeps O(n log n) time in general. You need to track how many copies of each value remain, which takes O(u) space. You could sort in place and mark used cards, but the scan for the next value then costs more time. The standard trade is O(n) space for O(n log n) time.
How do I solve LeetCode 846 in Python?
Return False if len(hand) % groupSize is nonzero. Build a Counter, loop over sorted(counts), and for each value with groups copies subtract groups from every value in the window value to value + groupSize - 1. Return False if any window value has fewer than groups copies, otherwise return True.
Why is the greedy choice correct in Hand of Straights?
The smallest remaining value x has nothing below it, so every copy of x is the lowest card of its group. That fixes k groups, each needing x through x + groupSize - 1. Any valid split contains exactly these cards, so taking them first never loses a solution.
Does the same idea solve LeetCode 1296?
Yes. Divide Array in Sets of K Consecutive Numbers asks the same question with k in place of groupSize. The same sorted count and window subtraction works unchanged.
Asked at
See which companies ask this — Pro
Related problems
- Merge Triplets to Form Target Triplet · same technique: Sorting Based
- Sort an Array · same technique: Sorting Based
- Two City Scheduling · same technique: Sorting Based
- Queue Reconstruction by Height · same technique: Sorting Based
- Candy · same technique: Sorting Based
- Merge Intervals · same pattern: Greedy Patterns
- Jump Game · same pattern: Greedy Patterns
- Gas Station · same pattern: Greedy Patterns
- Task Scheduler · same pattern: Greedy Patterns
- Non-overlapping Intervals · same pattern: Greedy Patterns