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.
This JavaScript solution sorts the input array and uses a loop to place numbers into non-repeating rows, starting a new row whenever necessary to maintain unique entries within each row.