⚡Flashcard Drill➔
NeetCode #144LC-2610MediumArrays & Hashing
← Back to All Problems

#144 · #2610 · Convert an Array Into a 2D Array With Conditions(转换二维数组)

📌 Problem Statement & Constraints

You are given an integer array nums. Create a 2D array where the i-th row contains the i-th occurrence of each distinct value, and pad shorter rows with zeros so the array is rectangular. Constraints: 1 <= nums.length <= 200, 1 <= nums[i] <= nums.length.

💡 Core Algorithmic Approaches

  1. Count the occurrences of each value.
  2. The number of rows equals the maximum frequency.
  3. For each distinct value, append it to the first freq rows.
  4. No zero padding is actually needed: the problem guarantees that the last row is fully populated, so the rows all end up the same length naturally.

💻 Benchmark Python3 Implementation

class Solution:
    def findMatrix(self, nums: List[int]) -> List[List[int]]:
        from collections import Counter
        cnt = Counter(nums)
        rows = [[] for _ in range(max(cnt.values()))]
        for v, c in cnt.items():
            for i in range(c):
                rows[i].append(v)          # i-th occurrence goes to row i
        return rows

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): counting plus distributing each occurrence once.
💾 Space Complexity
O(n) for the result.

⚠️ Interview Pitfalls & Follow-ups

  • Adding explicit zero padding: unnecessary, since each row receives one entry per value that occurs at least that many times, and the last row is guaranteed complete.
  • Sizing the row list by len(nums): the number of rows is the maximum frequency, not the array length.
  • Appending to the same row for all occurrences: the i-th occurrence must go to the i-th row.
  • Assuming values are unique: duplicates are the whole point of the problem.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems