DDSA Solutions

2625. Flatten Deeply Nested Array

Problem Overview

Flatten a nested array to depth n (or fully if depth is large).

Advertisement

Intuition

Flatten a nested array to depth n (or fully if depth is large). Each element is either an integer or another array — recurse into sub-arrays with depth-1 until depth is 0 or value is not an array.

Algorithm

  1. 1Define Flatten(arr, depth): if depth==0 or arr is int, return [arr].
  2. 2Otherwise iterate items: if item is array, extend result with Flatten(item, depth-1); else push item.
  3. 3Return accumulated list.

Example Walkthrough

Input: arr = [1,[2,[3]]], depth = 2

  1. 1.Depth 2: flatten outer → [1,2,[3]].
  2. 2.Inner [3] stays nested because depth exhausted.

Output: [1,2,[3]]

Common Pitfalls

  • Depth counts how many levels of nesting you may unwrap.
  • At depth 0, leave arrays as-is in the result.
  • Recursive or explicit stack both work.
2625.ts
TypeScript
type MultiDimensionalArray = (number | MultiDimensionalArray)[];

var flat = function (arr: MultiDimensionalArray, n: number): MultiDimensionalArray {
    function dfs(arr: number | MultiDimensionalArray, n: number) {
        if (typeof arr === 'number') {
            ans.push(arr);
        } else if (n === 0) {
            for (const element of arr) {
                ans.push(element);
            }
        } else {
            for (const element of arr) {
                dfs(element, n - 1);
            }
        }
    }
    const ans: MultiDimensionalArray = [];
    dfs(arr, n);
    return ans;
};
Advertisement
Was this solution helpful?

Related Problems