#2610
Medium Algorithms Convert an array into a 2d array with conditions
Array Hash Table
86.4% acceptance
Feb 25, 2026
1691
81
You are given an integer array nums. You need to create a 2D array from nums satisfying the following conditions:
The 2D array should contain only the elements of the array nums.
Each row in the 2D array contains distinct integers.
The number of rows in the 2D array should be minimal.
Return the resulting array. If there are multiple answers, return any of them.
Note that the 2D array can have a different number of elements on each row.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn find_matrix(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut count = std::collections::HashMap::new();
let mut result: Vec<Vec<i32>> = Vec::new();
for n in nums {
let cnt = count.entry(n).or_insert(0usize);
if *cnt >= result.len() {
result.push(Vec::new());
}
result[*cnt].push(n);
*cnt += 1;
}
result
}
}