<p>You are given an integer array <code>nums</code>. You need to create a 2D array from <code>nums</code> satisfying the following conditions:</p>

<ul>
	<li>The 2D array should contain <strong>only</strong> the elements of the array <code>nums</code>.</li>
	<li>Each row in the 2D array contains <strong>distinct</strong> integers.</li>
	<li>The number of rows in the 2D array should be <strong>minimal</strong>.</li>
</ul>

<p>Return <em>the resulting array</em>. If there are multiple answers, return any of them.</p>

<p><strong>Note</strong> that the 2D array can have a different number of elements on each row.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,3,4,1,2,3,1]
<strong>Output:</strong> [[1,3,4,2],[1,3],[1]]
<strong>Explanation:</strong> 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.</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> [[4,3,2,1]]
<strong>Explanation:</strong> All elements of the array are distinct, so we can keep all of them in the first row of the 2D array.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 200</code></li>
	<li><code>1 &lt;= nums[i] &lt;= nums.length</code></li>
</ul>

from collections import defaultdict

class Solution:
    def findMatrix(self, nums: List[int]) -> List[List[int]]:
        # Step 1: Count the frequency of each element in nums
        freq = defaultdict(int)
        for num in nums:
            freq[num] += 1
        
        # Step 2: Initialize the result list
        result = []
        
        # Step 3: Distribute elements to rows
        while freq:
            row = []
            keys_to_remove = []
            for num, count in freq.items():
                row.append(num)
                freq[num] -= 1
                if freq[num] == 0:
                    keys_to_remove.append(num)
            
            # Remove elements that were used in the current row
            for num in keys_to_remove:
                del freq[num]
            
            # Add the row to the result
            result.append(row)
        
        return result

# Example usage:
solution = Solution()
nums = [1, 3, 4, 1, 2, 3, 1]
print(solution.findMatrix(nums))  # Output: [[1, 3, 4, 2], [1, 3], [1]]
32