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.
1function convertArray(nums) {
2 const count = {};
3 nums.forEach(num => count[num] = (count[num] || 0) + 1);
4 const maxFrequency = Math.max(...Object.values(count));
5 const result = Array.from({length: maxFrequency}, () => []);
6 let index = 0;
7 for (let [num, frequency] of Object.entries(count)) {
8 for (let i = 0; i < frequency; i++) {
9 result[index].push(Number(num));
10 index = (index + 1) % maxFrequency;
11 }
12 }
13 return result;
14}
15
16// Example usage
17const nums = [1, 3, 4, 1, 2, 3, 1];
18console.log(convertArray(nums));
The JavaScript approach uses an object to track counts, calculates max frequency to determine the number of arrays needed, and distributes numbers over these arrays using a round-robin method.
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.