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
Convert Array Into 2D Array With Conditions1341231Input: [1,3,4,1,2,3,1]Row 1: [1, 3, 4, 2]Row 2: [1, 3]Row 3: [1]Output: 3 rows (minimum possible)
Understanding the Visualization
1
Input Array
Original 1D array with possible duplicates
2
Group by Frequency
Determine minimum rows needed = max frequency
3
Distribute Optimally
Create 2D array where each row has distinct elements
Key Takeaway
🎯 Key Insight: The minimum rows needed equals the maximum frequency of any element
Asked in
Google 15 Meta 12 Amazon 8
12.5K Views
Medium Frequency
~15 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen