Divide Array in Sets of K Consecutive Numbers

medium greedy hash map

Problem

Given an integer array nums and an integer k, determine whether nums can be partitioned into groups of k consecutive integers. Return true if possible.

Inputnums = [1, 2, 3, 3, 4, 4, 5, 6], k = 4
Outputtrue
Groups: [1,2,3,4] and [3,4,5,6]. Each is 4 consecutive integers.

from collections import Counter

def is_possible_divide(nums, k):
    if len(nums) % k: return False
    count = Counter(nums)
    for x in sorted(count):
        c = count[x]
        if c == 0: continue
        for j in range(k):
            if count[x + j] < c: return False
            count[x + j] -= c
    return True
function isPossibleDivide(nums, k) {
  if (nums.length % k) return false;
  const count = new Map();
  for (const x of nums) 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 j = 0; j < k; j++) {
      if ((count.get(x + j) || 0) < c) return false;
      count.set(x + j, count.get(x + j) - c);
    }
  }
  return true;
}
class Solution {
    public boolean isPossibleDivide(int[] nums, int k) {
        if (nums.length % k != 0) return false;
        TreeMap<Integer, Integer> count = new TreeMap<>();
        for (int x : nums) count.merge(x, 1, Integer::sum);
        while (!count.isEmpty()) {
            int x = count.firstKey();
            int c = count.get(x);
            for (int j = 0; j < k; j++) {
                int v = count.getOrDefault(x + j, 0);
                if (v < c) return false;
                if (v == c) count.remove(x + j);
                else count.put(x + j, v - c);
            }
        }
        return true;
    }
}
bool isPossibleDivide(vector<int>& nums, int k) {
    if ((int)nums.size() % k) return false;
    map<int, int> count;
    for (int x : nums) count[x]++;
    while (!count.empty()) {
        int x = count.begin()->first;
        int c = count.begin()->second;
        for (int j = 0; j < k; j++) {
            if (count[x + j] < c) return false;
            count[x + j] -= c;
            if (count[x + j] == 0) count.erase(x + j);
        }
    }
    return true;
}
Time: O(n log n + n · k) Space: O(n)