We need to distribute numbers into rows such that each row contains only distinct elements. For each number, we find the first row where it doesn't already exist and place it there. If no such row exists, we create a new row. This greedy placement ensures we use the minimum number of rows needed.
0 and search for a row that doesn't contain this number.Where is the size of the array and is the frequency of the most frequent element in the given array.
By sorting the array first, all identical numbers become adjacent. This allows us to process each group of duplicates together. The number of rows needed equals the maximum frequency of any element, and by distributing each group of identical elements across consecutive rows starting from row 0, we ensure each row has distinct values.
0.class Solution:
def findMatrix(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
i = 0
while i < len(nums):
j = i
r = 0
while j < len(nums) and nums[i] == nums[j]:
if r == len(res):
res.append([])
res[r].append(nums[i])
r += 1
j += 1
i = j
return resThe frequency of each number tells us exactly which row it should go into. The first occurrence goes to row 0, the second occurrence to row 1, and so on. By tracking how many times we've seen each number, we can directly place it in the correct row without searching. This eliminates the need for both sorting and linear searching.
0 for all).A common mistake is using the frequency count incorrectly as the row index. The row where an element should go is determined by how many times it has been placed so far, not its total frequency in the array.
# Wrong - using total frequency
row = total_count[num]
# Correct - using count of placements so far
row = count[num] # then increment count[num] after placingForgetting to create a new row when needed leads to index out of bounds errors. Before placing an element in a row, check if that row exists.
# Wrong - crashes if row doesn't exist
res[row].append(num)
# Correct - create row if needed
if len(res) == row:
res.append([])
res[row].append(num)In the brute force approach, checking if a number exists in a row using linear search on every insert leads to O(n * m) complexity. While acceptable for the brute force solution, be aware that the frequency count approach achieves O(n) by avoiding these repeated searches entirely.