#3659
Medium Algorithms Partition array into k distinct groups
Array Hash Table Counting
47.0% acceptance
Feb 25, 2026
112
72
You are given an integer array nums and an integer k.
Your task is to determine whether it is possible to partition all elements of nums into one or more groups such that:
Each group contains exactly k elements.
All elements in each group are distinct.
Each element in nums must be assigned to exactly one group.
Return true if such a partition is possible, otherwise return false.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn partition_array(nums: Vec<i32>, k: i32) -> bool {
let n = nums.len() as i32;
if n % k != 0 { return false; }
let groups = (n / k) as usize;
let mut freq = std::collections::HashMap::new();
for x in &nums { *freq.entry(x).or_insert(0usize) += 1; }
freq.values().all(|&cnt| cnt <= groups)
}
}