Hand of Straights

medium greedy hash-map sorting

Problem

Given an array of integers hand and an integer groupSize, return true if the hand can be partitioned into groups of size groupSize where each group is a run of consecutive integers.

Inputhand = [1,2,3,6,2,3,4,7,8], groupSize = 3
Outputtrue
Partition into [1,2,3], [2,3,4], [6,7,8].

from collections import Counter

def isNStraightHand(hand, groupSize):
    if len(hand) % groupSize: return False
    count = Counter(hand)
    for x in sorted(count):
        c = count[x]
        if c == 0: continue
        for k in range(groupSize):
            if count[x + k] < c: return False
            count[x + k] -= c
    return True
function isNStraightHand(hand, groupSize) {
  if (hand.length % groupSize) return false;
  const count = new Map();
  for (const x of hand) count.set(x, (count.get(x) || 0) + 1);
  const keys = [...count.keys()].sort((a, b) => a - b);
  for (const x of keys) {
    const c = count.get(x);
    if (c === 0) continue;
    for (let k = 0; k < groupSize; k++) {
      if ((count.get(x + k) || 0) < c) return false;
      count.set(x + k, count.get(x + k) - c);
    }
  }
  return true;
}
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 x : hand) count.merge(x, 1, Integer::sum);
    for (int x : new ArrayList<>(count.keySet())) {
      int c = count.getOrDefault(x, 0);
      if (c == 0) continue;
      for (int k = 0; k < groupSize; k++) {
        if (count.getOrDefault(x + k, 0) < c) return false;
        count.merge(x + k, -c, Integer::sum);
      }
    }
    return true;
  }
}
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    bool isNStraightHand(vector<int>& hand, int groupSize) {
        if (hand.size() % groupSize) return false;
        map<int,int> count;
        for (int x : hand) count[x]++;
        for (auto &[x, _] : count) {
            int c = count[x];
            if (c == 0) continue;
            for (int k = 0; k < groupSize; k++) {
                if (count[x + k] < c) return false;
                count[x + k] -= c;
            }
        }
        return true;
    }
};
Time: O(n log n) Space: O(n)