Hand of Straights

Decide whether a hand of cards can be split into runs of consecutive values, all of the same length.

Given a hand of cards as an array of integers hand and a number groupSize, decide whether the cards can be split into groups of exactly groupSize cards each, where the values in every group are consecutive, such as 6, 7, 8. Every card must go into exactly one group. Return true if such a split exists, and false otherwise.

Example 1
Input: hand = [1, 2, 3, 6, 2, 3, 4, 7, 8], groupSize = 3
Output: true
Explanation: the cards form [1, 2, 3], [2, 3, 4] and [6, 7, 8].
Example 2
Input: hand = [1, 2, 3, 4, 5], groupSize = 4
Output: false
Explanation: 5 cards cannot be split into groups of 4.
Solution

The Idea

In card games, a run of cards whose values follow one another, like 6, 7, 8, is called a straight. This problem hands us a pile of cards and asks whether all of them can be laid out as straights of the same length, with no card left over.

Take Example 1. Its nine cards, sorted, are 1, 2, 2, 3, 3, 4, 6, 7, 8, and each straight must have three cards. The 2 and the 3 appear twice, so each copy could join a different straight. Which straight should each card join? The number of ways to share out the cards grows quickly as the hand gets bigger.

Look at the card 1 instead. No card in the hand is smaller, so 1 cannot sit in the middle or at the end of a straight: nothing could come before it. Card 1 has to start a straight, and that straight must be 1, 2, 3. There is no choice to make.

Once 1, 2 and 3 are put aside, the same reasoning works for the cards that are left. Look at the picture below.

The hand 1, 2, 2, 3, 3, 4, 6, 7, 8 in sorted order. Round 1: the smallest card left, 1, starts the group 1, 2, 3. Round 2: the smallest card left, 2, starts 2, 3, 4. Round 3: the smallest card left, 6, starts 6, 7, 8.

The orange card in each row is the smallest card left, the blue cards complete its straight, and the dashed grey cards are already used. In the row labelled "round 2", the smallest card left is the second 2, so it starts 2, 3, 4. In the row labelled "round 3", only 6, 7 and 8 remain, and 6 starts the last straight. Every card is used, so the answer is true.

The same rule also shows when the answer is false. With the hand [1, 3, 4, 5] and straights of two cards, card 1 must start 1, 2, but the hand has no 2. Nothing else could fix that, so the hand cannot be split.

Building the answer one straight at a time, each time from the smallest card left, and never going back to change a straight already laid out, is called a greedy approach. It works here because the smallest card's straight is forced, so no other choice could have done better.

Solution Approach

Turning that idea into code means settling three things: a quick check on the number of cards, how to find the smallest card left, and how to take one copy of each card in a straight.

Counting the cards first

Can some hands be ruled out at once? Every straight has groupSize cards, so the hand must have a multiple of groupSize cards. In Example 2, five cards cannot fill straights of four, so the answer is false before any straight is built.

Finding the smallest card left

How do we find the smallest card left, round after round? The plain way is to scan the whole hand each time a straight starts. With many short straights, that repeats a scan of every card once per straight.

A better way keeps the cards in a map from card value to how many copies of it are left. For Example 1 the map is {1=1, 2=2, 3=2, 4=1, 6=1, 7=1, 8=1}. Here the map is a TreeMap, which keeps its keys, the card values, in sorted order. So firstKey() returns the smallest card left without a scan.

Taking one copy of each card

What happens to the map when a straight is laid out? For each of the groupSize values starting at the smallest card, one copy is taken. If a value is missing from the map, the straight has a gap and the answer is false.

When a value's last copy is taken, its entry is removed rather than set to 0. Otherwise firstKey() could return a card the hand no longer holds. In Example 1, round 1 takes the only 1 and drops that entry. It leaves one copy each of 2 and 3, which is why the map then starts at 2.

Java Solution

The method isNStraightHand works in these steps:

  1. First, check hand.length % groupSize. If it is not 0, the cards cannot fill whole straights, so return false.
  2. Build count, a TreeMap from card value to number of copies, by calling count.merge(card, 1, Integer::sum) for each card in the hand.
  3. While count is not empty, read the smallest card left with count.firstKey() into start.
  4. Inside, a second loop moves card from start up to start + groupSize - 1. For each value it reads the number of copies, c, with count.get(card). If c is null, the value is missing and the method returns false. If c is 1, the entry is removed; otherwise it becomes c - 1.
  5. When count is empty, every card is in a straight, so return true.

The main method runs both examples, a hand with a gap, a hand of repeated pairs, a hand that is not in sorted order, and straights of one card.

Java
import java.util.TreeMap;

public class HandOfStraights {

    public static boolean isNStraightHand(int[] hand, int groupSize) {
        if (hand.length % groupSize != 0) {
            return false;                     // the cards cannot fill whole straights
        }
        TreeMap<Integer, Integer> count = new TreeMap<>();
        for (int card : hand) {
            count.merge(card, 1, Integer::sum);
        }
        while (!count.isEmpty()) {
            int start = count.firstKey();     // the smallest card must start a straight
            for (int card = start; card < start + groupSize; card++) {
                Integer c = count.get(card);
                if (c == null) {
                    return false;             // the straight would have a gap
                }
                if (c == 1) {
                    count.remove(card);       // last copy: drop the value
                } else {
                    count.put(card, c - 1);
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isNStraightHand(new int[] {1, 2, 3, 6, 2, 3, 4, 7, 8}, 3));
        System.out.println(isNStraightHand(new int[] {1, 2, 3, 4, 5}, 4));
        System.out.println(isNStraightHand(new int[] {1, 3, 4, 5}, 2));
        System.out.println(isNStraightHand(new int[] {1, 1, 2, 2}, 2));
        System.out.println(isNStraightHand(new int[] {2, 1, 3, 4}, 2));
        System.out.println(isNStraightHand(new int[] {5, 9, 7}, 1));
    }
}

Running it prints:

Output
true
false
false
true
true
true

Example 1 gives true and Example 2 gives false, as expected. Look at the third line: [1, 3, 4, 5] has four cards, which split evenly into pairs, yet it prints false. Card 1 needs a 2 to start its pair, and the inner loop finds no 2 in the map.

The fourth line, for [1, 1, 2, 2], is true. After the first pair 1, 2 takes one copy of each value, 1 is still the smallest card left, and it starts a second 1, 2.

The fifth line, for [2, 1, 3, 4], is true, with the pairs 1, 2 and 3, 4. Here the smallest card matters. A version that starts each pair at the next card in input order takes 2, 3 first and is left with 1 and 4, which are not consecutive. That version returns false for this hand. The last line shows that with groupSize 1, every card is a straight on its own, so the answer is true.

Complexity

The work is one map update for each card when the map is built, and one more when that card goes into a straight.

  • Time: O(n log n), because each of the n cards costs one merge to count it and one get plus a put or remove to place it, and each TreeMap call takes O(log n) steps on a map of at most n entries.
  • Space: O(n), because the map holds one entry for each different card value, which is n entries when no two cards are equal.

Starting from the smallest item, because its role is forced, also drives Assign Cookies, which serves the child who is easiest to satisfy first.