2 minute read

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

The 2D array should contain only the elements of the array nums. Each row in the 2D array contains distinct integers. The number of rows in the 2D array should be minimal. Return the resulting array. If there are multiple answers, return any of them.

Note that the 2D array can have a different number of elements on each row.

Example 1:

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

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

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var findMatrix = function (nums) {
  // create a map
  const map = {};
  // create a result array
  let result = [];

  // loop through the nums
  for (const num of nums) {
    // if the num is in the map
    if (num in map) {
      // add the num to the map
      map[num] = map[num] + 1;
    } else {
      // Otherwise, add the num to the map
      map[num] = 1;
    }
  }

  // loop through the map
  for (const key in map) {
    // loop through each key
    for (let i = 0; i < map[key]; i++) {
      // if the result[i] is undefined which means the row is empty
      if (result[i] === undefined) {
        // add the key to the result
        result[i] = [key];
      } else {
        // Otherwise, push the key to the result
        result[i].push(key);
      }
    }
  }
  // return the result
  return result;
};

// Time Complexity: O(n), because the function loops through the nums array once and the map once as well. So, the time complexity is O(n + n) = O(n). n is the length of the nums array. // Space Complexity: O(n), because the function creates a map and a result array. So, the space complexity is O(n + n) = O(n). n is the length of the nums array.

Leave a comment