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.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- 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.
Use this to learn the idea, then write your own version.
1function jsonToMatrix(arr: any[]): (string | number | boolean | null)[][] {2 const isObject = (o: any) => o !== null && typeof o === 'object';3 4 5 const getKeys = (json: any): string[] => {6 if (!isObject(json)) {7 return [''];8 }9 return Object.keys(json).reduce((acc: string[], currKey: string) => {10 return (11 acc.push(12 ...getKeys(json[currKey]).map((nextKey: string) =>13 nextKey === '' ? currKey : `${currKey}.${nextKey}`14 )15 ),16 acc17 );18 }, []);19 };20 21 const sortedKeys: string[] = [22 ...arr.reduce((acc: Set<string>, curr: any) => {23 getKeys(curr).forEach((key: string) => acc.add(key));24 return acc;25 }, new Set<string>()),26 ].sort();27 28 29 const getValue = (30 obj: any,31 nestedKey: string32 ): string | number | boolean | null => {33 let value: any = obj;34 for (const key of nestedKey.split('.')) {35 if (!isObject(value) || !(key in value)) {36 return '';37 }38 value = value[key];39 }40 return isObject(value) ? '' : value;41 };42 43 const matrix: (string | number | boolean | null)[][] = [sortedKeys];44 arr.forEach((obj: any) => {45 matrix.push(46 sortedKeys.map((nestedKey: string) => getValue(obj, nestedKey))47 );48 });49 50 return matrix;51}52