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 to 2D Array INPUT Integer Array nums: 1 3 4 1 2 3 1 Frequency Count: Element : Count 1 : 3 3 : 2 4 : 1 2 : 1 Max freq = 3 rows ALGORITHM STEPS 1 Count Frequencies Use HashMap to count each element occurrence 2 Find Max Frequency Max freq = min rows needed (here: 3) 3 Distribute Elements Place each element in different rows (distinct) 4 Build Result Add to row i, decrement count, move to next row Distribution Process: Row 0: 1,3,4,2 (unique) Row 1: 1,3 (remaining) Row 2: 1 (last copy) FINAL RESULT 2D Array Output: Row 0: 1 3 4 2 Row 1: 1 3 Row 2: 1 [[1,3,4,2],[1,3],[1]] OK - Valid Output Verification: - All elements used - Each row has distinct values - Minimal rows (3 = max freq) Key Insight: The minimum number of rows needed equals the maximum frequency of any element. Each occurrence of an element must go to a different row to maintain distinctness. TutorialsPoint - Convert an Array Into a 2D Array With Conditions | Optimal Solution
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