Algo-Sim › Greedy
Hand of Straights
Medium · Greedy · step through it in Java, Python and C++ on your own input
Can the cards be split into groups of groupSize consecutive values? The smallest card left must start a group, so build runs from it.
Problem
Given card values hand and a group size groupSize, decide whether all the cards can be split into groups of exactly groupSize cards whose values are consecutive (such as 3, 4, 5). Every card must be used once.
Constraints
- 1 ≤ hand.length ≤ 10⁴
- 0 ≤ hand[i] ≤ 10⁹
- 1 ≤ groupSize ≤ hand.length
- hand.length must be a multiple of groupSize
Edge cases to test
- n not divisible by groupSize:
false - groupSize = 1: always
true - Duplicates spread over several groups
Follow-up questions
- Why must the smallest card start a group?
- Nothing smaller can extend it, so it can only be the first card of some run: the greedy is forced.
- Can it beat O(n log n)?
- Sorting the distinct values dominates. A trick: start from any card and walk down to its run’s lowest value first, giving O(n) expected with a hash map.
Solution
Java
public boolean isNStraightHand(int[] hand, int groupSize) {
if (hand.length % groupSize != 0) return false;
TreeMap<Integer, Integer> count = new TreeMap<>();
for (int card : hand) count.merge(card, 1, Integer::sum);
while (!count.isEmpty()) {
int first = count.firstKey();
for (int card = first; card < first + groupSize; card++) {
Integer c = count.get(card);
if (c == null) return false;
if (c == 1) count.remove(card);
else count.put(card, c - 1);
}
}
return true;
}Python
from collections import Counter
def is_n_straight_hand(hand, group_size):
if len(hand) % group_size:
return False
count = Counter(hand)
while count:
first = min(count)
for card in range(first, first + group_size):
if card not in count:
return False
count[card] -= 1
if count[card] == 0:
del count[card]
return TrueC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isNStraightHand(vector<int> &hand, int groupSize) {
if (int(hand.size()) % groupSize != 0)
return false;
map<int, int> count = {};
for (int card : hand)
count[card] += 1;
while (!count.empty()) {
int first = count.begin()->first;
for (int card = first; card < first + groupSize; card++) {
int c = count[card];
if (c == 0)
return false;
if (c == 1)
count.erase(card);
else
count[card] = c - 1;
}
}
return true;
}
};
More Greedy problems
- Maximum Subarray (Medium)
- Best Time to Buy and Sell Stock II (Medium)
- Jump Game (Medium)
- Jump Game II (Medium)
- Gas Station (Medium)
- Partition Labels (Medium)
- Task Scheduler (Medium)
- Merge Triplets to Form Target Triplet (Medium)
- Valid Parenthesis String (Medium)
- Minimum Number of Arrows to Burst Balloons (Medium)
- Candy (Hard)
- Boats to Save People (Medium)
- Two City Scheduling (Medium)