Problem solution · TypeScript

Array of Objects to Matrix

Array of Objects to Matrix: a TypeScript solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
52 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Array of Objects to Matrix, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 52 lines of TypeScript from the credited upstream file 2675.ts.
  • The implementation visibly relies on sequence storage, ordered lookup.
  • 1 loop block detected.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeArray of Objects to Matrix · TypeScriptTypeScript
Use this to learn the idea, then write your own version.
function jsonToMatrix(arr: any[]): (string | number | boolean | null)[][] {  const isObject = (o: any) => o !== null && typeof o === 'object';   // Returns the keys of a JSON-like object by recursively unwrapping the nests.  const getKeys = (json: any): string[] => {    if (!isObject(json)) {      return [''];    }    return Object.keys(json).reduce((acc: string[], currKey: string) => {      return (        acc.push(          ...getKeys(json[currKey]).map((nextKey: string) =>            nextKey === '' ? currKey : `${currKey}.${nextKey}`          )        ),        acc      );    }, []);  };   const sortedKeys: string[] = [    ...arr.reduce((acc: Set<string>, curr: any) => {      getKeys(curr).forEach((key: string) => acc.add(key));      return acc;    }, new Set<string>()),  ].sort();   // Returns the value of `obj` keyed by `nestedKey`.  const getValue = (    obj: any,    nestedKey: string  ): string | number | boolean | null => {    let value: any = obj;    for (const key of nestedKey.split('.')) {      if (!isObject(value) || !(key in value)) {        return '';      }      value = value[key];    }    return isObject(value) ? '' : value;  };   const matrix: (string | number | boolean | null)[][] = [sortedKeys];  arr.forEach((obj: any) => {    matrix.push(      sortedKeys.map((nestedKey: string) => getValue(obj, nestedKey))    );  });   return matrix;} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗