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

Edge cases to test

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 True

C++

#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