Magicsheet logo

Flatten Deeply Nested Array

Medium
82.5%
Updated 6/1/2025

Flatten Deeply Nested Array

1. What is this problem about?

The Flatten Deeply Nested Array interview question is a common JavaScript/Frontend challenge. You are given an array that can contain integers or other arrays (which can also be nested). You are also given a depth DD. Your goal is to flatten the array up to DD levels deep. If D=0D=0, no flattening occurs. If D=1D=1, only the first level of nesting is removed.

2. Why is this asked in interviews?

Companies like Apple and TikTok ask this to evaluate a candidate's understanding of Recursion and array manipulation. It tests your ability to handle non-uniform data structures (heterogeneous arrays) and manage a depth constraint. It is a fundamental exercise in writing recursive functions with base cases.

3. Algorithmic pattern used

This problem follows the Recursive Traversal with Depth Tracking pattern.

  1. Iterate: Loop through every element in the input array.
  2. Base Case: If the element is not an array OR if the current depth is 0, add the element as-is to the result.
  3. Recursive Step: If the element is an array and depth > 0, call the flatten function on this sub-array with depth - 1. Append all elements from the recursive result to your current result.
  4. Iterative Alternative: Use a stack to process elements, keeping track of their depth.

4. Example explanation

Input: [1, [2, [3, 4]], 5], Depth D=1D = 1.

  1. 1 is not an array. Result: [1].
  2. [2, [3, 4]] is an array and D>0D > 0.
    • Recursive call with D=0D=0: [2, [3, 4]] -> returns [2, [3, 4]].
    • Add elements to Result: [1, 2, [3, 4]].
  3. 5 is not an array. Result: [1, 2, [3, 4], 5]. If D=2D=2, the inner [3, 4] would also have been flattened.

5. Common mistakes candidates make

  • Ignoring Depth: Flattening the entire array regardless of the DD parameter.
  • Inefficient Appending: Using push(...recursiveCall) in languages like JavaScript, which can hit argument limits for very large arrays. Using a simple loop or concat is safer.
  • Type checking errors: Not correctly identifying if an element is an array.

6. Interview preparation tip

Get comfortable with Recursive vs. Iterative solutions. Recursion is often easier to write, but an iterative solution using a stack is more robust against "Stack Overflow" errors for extremely deep nestings (e.g., depth 10,000).

Similar Questions