#2610

Convert an Array Into a 2D Array With Conditions

Medium
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a frequency map to count occurrences of each number. We then distribute these numbers into rows based on their frequency, ensuring that each row contains distinct integers and minimizing the number of rows needed.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a frequency map to count how many times each number appears in the input array.
  2. 2Step 2: Determine the maximum frequency from the frequency map, which will dictate the number of rows needed.
  3. 3Step 3: Create an empty 2D array with the number of rows equal to the maximum frequency.
  4. 4Step 4: Distribute the numbers into the rows based on their frequency, ensuring each row contains distinct integers.
solution.py10 lines
1from collections import Counter
2
3def convertArray(nums):
4    freq = Counter(nums)
5    max_freq = max(freq.values())
6    result = [[] for _ in range(max_freq)]
7    for num, count in freq.items():
8        for i in range(count):
9            result[i].append(num)
10    return result

Complexity note: The time complexity is O(n) because we traverse the input array to build the frequency map and then distribute the numbers into rows. The space complexity is O(n) due to the storage of the frequency map and the result array.

  • 1Using a frequency map allows us to efficiently distribute elements into rows based on their occurrences.
  • 2The number of rows needed is determined by the maximum frequency of any element.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.