Skip to main content
Back to problems
#1296
Medium Algorithms

Divide array in sets of k consecutive numbers

Array Hash Table Greedy Sorting
59.1% acceptance
Feb 25, 2026
1982
118
Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers. Return true if it is possible. Otherwise, return false.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn is_possible_divide(nums: Vec<i32>, k: i32) -> bool {
    use std::collections::BTreeMap;
    if nums.len() % k as usize != 0 { return false; }
    let mut counts: BTreeMap<i32, i32> = BTreeMap::new();
    for &x in &nums { *counts.entry(x).or_default() += 1; }
    while let Some((&min_val, _)) = counts.iter().next() {
      let freq = *counts.get(&min_val).unwrap();
      if freq == 0 { counts.remove(&min_val); continue; }
      for i in 0..k {
        let v = min_val + i;
        let e = counts.entry(v).or_default();
        if *e < freq { return false; }
        *e -= freq;
        if *e == 0 { counts.remove(&v); }
      }
    }
    true
  }
}