Convert an Array Into a 2D Array With Conditions Problem
Description
LeetCode Problem 2610.
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.
Example 1:
Input: nums = [1,3,4,1,2,3,1]
Output: [[1,3,4,2],[1,3],[1]]
Explanation: We can create a 2D array that contains the following rows:
- 1,3,4,2
- 1,3
- 1
All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer.
It can be shown that we cannot have less than 3 rows in a valid array.
Example 2:
Input: nums = [1,2,3,4]
Output: [[4,3,2,1]]
Explanation: All elements of the array are distinct, so we can keep all of them in the first row of the 2D array.
Constraints:
1 <= nums.length <= 2001 <= nums[i] <= nums.length
Solution
Approach: Count, Then Deal Out
A row cannot hold the same value twice, so a value that occurs c times needs at least c rows. The most frequent value therefore sets the minimum number of rows, and we can reach that minimum.
Count how often each value occurs. Then, for each value x with count c, put one copy of x into each of rows 0, 1, ..., c - 1, creating rows when they do not exist yet. Every row gets each value at most once, and the number of rows equals the largest count.
Complexity: O(n) time and O(n) space, where n is the length of nums.
from collections import Counter
class Solution:
def findMatrix(self, nums: List[int]) -> List[List[int]]:
cnt = Counter(nums)
ans = []
for x, v in cnt.items():
for i in range(v):
if len(ans) <= i:
ans.append([])
ans[i].append(x)
return ans