Sponsored
Sponsored
The main idea is to utilize a hash map (or dictionary) to count the occurrences of each element in the input array. This helps us determine how many rows we will need based on the maximum frequency of any element.
Then, we iteratively fill the 2D array by distributing each unique element to different rows, ensuring each row contains distinct integers.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(n), because of the storage needed for the count map and result array.
1def convertArray(nums):
2 from collections import defaultdict
3 count = defaultdict(int)
4 for num in nums:
5 count[num] += 1
6 max_frequency = max(count.values())
7 result = [[] for _ in range(max_frequency)]
8 index = 0
9 for num, frequency in count.items():
10 for _ in range(frequency):
11 result[index].append(num)
12 index = (index + 1) % max_frequency
13 return result
14
15# Example usage
16nums = [1, 3, 4, 1, 2, 3, 1]
17print(convertArray(nums))
The Python solution uses a defaultdict to count occurrences of each element in the array. Then, based on the maximum frequency, it creates the necessary rows in the result array. Using a greedy round-robin method, it fills rows while iterating over each element's frequency.
This approach first sorts the array to easily group identical elements. Starting from the least element, it places each new occurrence in different rows to ensure minimal rows while adhering to the distinct integer rule per row.
Time Complexity: O(n log n), because of sorting.
Space Complexity: O(n), for storing the result array.
1using System.Collections.Generic;
public class Solution {
public static List<List<int>> ConvertArray(int[] nums) {
Array.Sort(nums);
List<List<int>> result = new List<List<int>>();
foreach (var num in nums) {
bool placed = false;
foreach (var row in result) {
if (!row.Contains(num)) {
row.Add(num);
placed = true;
break;
}
}
if (!placed) {
List<int> newRow = new List<int>();
newRow.Add(num);
result.Add(newRow);
}
}
return result;
}
public static void Main() {
int[] nums = {1, 3, 4, 1, 2, 3, 1};
var result = ConvertArray(nums);
foreach (var row in result) {
Console.WriteLine(string.Join(" ", row));
}
}
}
The C# implementation sorts the array, tries to place each integer in existing non-repetitive rows, creating new ones when required, thus ensuring minimum necessary rows.