Ecommet

Hand of Straights

Medium Problem 138 of 151 Java and Python

Problem

Alice has cards with values hand[i]. She wants to rearrange them into groups of size groupSize, where each group is groupSize consecutive values.

Return true if she can, otherwise false.

Example 1

Input
hand = [1, 2, 3, 6, 2, 3, 4, 7, 8], groupSize = 3
Output
true
Why
[1, 2, 3], [2, 3, 4], [6, 7, 8].

Example 2

Input
hand = [1, 2, 3, 4, 5], groupSize = 4
Output
false

Constraints

  • 1 ≤ hand.length ≤ 10⁴
  • 1 ≤ groupSize ≤ hand.length

Explanation

The smallest card left can only be the start of a group (nothing smaller is available to come before it). So the greedy choice is forced: start a group at the smallest card and take the next groupSize - 1 values. If any is missing, fail.

Approach 1 · Better

Sort and remove from a list

  • Time O(n²) because of list removals
  • Space O(n)

Sort the cards; repeatedly take the smallest and remove one of each following value from the list.

  1. If n % groupSize != 0, return false.
  2. Sort into a list. While it is not empty: take the first value v, and remove v, v + 1, …, v + groupSize - 1 (fail if one is missing).
Java
import java.util.*;

class Solution {
    public boolean isNStraightHand(int[] hand, int groupSize) {
        if (hand.length % groupSize != 0) {
            return false;
        }
        List<Integer> cards = new ArrayList<>();
        for (int card : hand) {
            cards.add(card);
        }
        Collections.sort(cards);
        while (!cards.isEmpty()) {
            int first = cards.get(0);
            for (int v = first; v < first + groupSize; v++) {
                if (!cards.remove(Integer.valueOf(v))) {
                    return false;
                }
            }
        }
        return true;
    }
}
Python
class Solution:
    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
        if len(hand) % groupSize:
            return False
        cards = sorted(hand)
        while cards:
            first = cards[0]
            for v in range(first, first + groupSize):
                if v not in cards:
                    return False
                cards.remove(v)
        return True

Approach 2 · Optimal

Sorted counts

  • Time O(n log n)
  • Space O(n)

Count each value. Walk the distinct values in increasing order; every remaining copy of value v must start a group, which uses that many copies of v + 1 … v + groupSize - 1.

  1. Count cards in a sorted map.
  2. For each value v with need = count[v] > 0: for each k in 1 … groupSize - 1, if count[v + k] < need return false, else subtract need.
  3. Return true.
Java
import java.util.*;

class Solution {
    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);
        }
        for (int v : count.keySet()) {
            int need = count.get(v);
            if (need == 0) {
                continue;
            }
            for (int k = 1; k < groupSize; k++) {
                int have = count.getOrDefault(v + k, 0);
                if (have < need) {
                    return false;
                }
                count.put(v + k, have - need);
            }
        }
        return true;
    }
}
Python
from collections import Counter

class Solution:
    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
        if len(hand) % groupSize:
            return False
        count = Counter(hand)
        for v in sorted(count):
            need = count[v]
            if need == 0:
                continue
            for k in range(1, groupSize):
                if count[v + k] < need:
                    return False
                count[v + k] -= need
        return True

Complexity compared

ApproachTimeSpace
Better Sort and remove from a listO(n²) because of list removalsO(n)
Optimal Sorted countsO(n log n)O(n)

Key takeaways

  • When the extreme element (smallest, largest) has only one possible role, assign it greedily.
  • This is the same problem as "Divide Array in Sets of K Consecutive Numbers".

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem