↻one more pass.
Greedy · Medium

Hand of Straights: the idea to remember.

Determine whether a multiset of cards can be split into equal sized groups of consecutive values.

Solve on LeetCode ↗

The core insight

Start a group at the smallest remaining value and remove one occurrence of each required consecutive card.

Why it works

The smallest unused card cannot be placed after any smaller unused card, so it must start its next group.

The mistake to avoid

Check counts rather than just distinct membership; duplicates may start several separate groups.

Time: O(n log n)Space: O(n)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Start a group at the smallest remaining value and remove one occurrence of each required consecutive card.
public boolean isNStraightHand(int[] hand, int groupSize) {
    if (hand.length % groupSize != 0) return false;

    HashMap<Integer, Integer> hm = new HashMap<>();
    for (int card : hand) hm.put(card, hm.getOrDefault(card, 0) + 1);

    Arrays.sort(hand);
    for (int card : hand) {
        if (hm.get(card) <= 0) continue;
        for (int i = 1; i < groupSize; i++) {
            int count = hm.getOrDefault(card + i, 0);
            if (count > 0) hm.put(card + i, count - 1); else return false;
        }
        hm.put(card, hm.get(card) - 1);
    }

    return true;
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.