Convert an Array Into a 2D Array With Conditions - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,3,4,1,2,3,1]
›
Output:
[[1,3,4,2],[1,3],[1]]
💡 Note:
Number 1 appears 3 times (most frequent), so we need 3 rows minimum. Distribute: Row 1 gets [1,3,4,2], Row 2 gets [1,3], Row 3 gets [1]
Example 2 — All Unique
$
Input:
nums = [1,2,3,4]
›
Output:
[[1,2,3,4]]
💡 Note:
All numbers are unique, so only 1 row needed containing all elements
Example 3 — All Same
$
Input:
nums = [1,1,1,1]
›
Output:
[[1],[1],[1],[1]]
💡 Note:
All numbers are the same, so each must go in a separate row to maintain distinctness
Constraints
- 1 ≤ nums.length ≤ 200
- 1 ≤ nums[i] ≤ nums.length
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code