⚡Flashcard Drill➔
NeetCode #962LC-2675MediumJavaScript
← Back to All Problems

#962 · #2675 · Array of Objects to Matrix(将对象数组转换为矩阵)

📌 Problem Statement & Constraints

Given an array of nested objects arr, return a matrix whose first row lists all leaf-key paths (dot-joined, sorted lexicographically) and whose later rows hold each object's values for those paths; a missing path yields an empty string.

💡 Core Algorithmic Approaches

  1. First pass: recursively walk every object and collect all leaf paths (for example a.b.c).
  2. Deduplicate the paths and sort them lexicographically to form the header row.
  3. For each object, read the value at each header path in order; a missing path, or one that resolves to an object, becomes an empty string.
  4. The exercise combines path flattening, lexicographic sorting, and path-based lookup.

💻 Benchmark Python3 Implementation

var jsonToMatrix = function(arr) {
    const keys = new Set();

    // Recursively flatten and collect every leaf path
    const collect = (obj, prefix) => {
        for (const k of Object.keys(obj)) {
            const v = obj[k];
            const path = prefix ? prefix + "." + k : k;
            if (v !== null && typeof v === "object") {
                collect(v, path);
            } else {
                keys.add(path);
            }
        }
    };
    for (const o of arr) collect(o, "");

    const header = [...keys].sort();          // lexicographic header

    // Read a path; a missing path or an object value yields an empty string
    const get = (obj, path) => {
        let cur = obj;
        for (const p of path.split(".")) {
            if (cur === null || typeof cur !== "object" || !(p in cur)) {
                return "";
            }
            cur = cur[p];
        }
        return cur !== null && typeof cur === "object" ? "" : cur;
    };

    const res = [header];
    for (const o of arr) {
        res.push(header.map(k => get(o, k)));
    }
    return res;
};

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(m * k): m objects times k total leaf paths.
💾 Space Complexity
O(m * k): the result matrix.

⚠️ Interview Pitfalls & Follow-ups

  • Treating nested objects as leaves: recursion must descend to primitive values only.
  • Not sorting the header: the problem requires lexicographic order (the default string sort suffices).
  • Filling a missing path with undefined: the required filler is an empty string.
  • Testing existence with cur[p] instead of p in cur: the two differ when the stored value is undefined.
⚡
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 JavaScript Problems