CodingMedium Arrays & Hashing

Flatten a Nested Array

Asked for all developer roles

Why they ask this: Tests recursion and how you handle data of unknown depth, which is common with JSON from APIs.

Problem

Given an array that can contain numbers and other arrays nested to any depth, return a single flat array with all the values in their original order.

Example

text
Input:  [1, [2, [3, [4]], 5], [], 6]
Output: [1, 2, 3, 4, 5, 6]

Hints

    Approach

    Recursive: create an empty result. For each item, if it is an array, flatten it recursively and append its values; otherwise append the item itself.

    Iterative alternative: use a stack seeded with the input's items in reverse. Pop an item; if it is an array, push its children in reverse; otherwise append it to the result. This avoids stack overflow for extremely deep nesting.

    Built-ins: arr.flat(Infinity) in JavaScript; in PHP, array_walk_recursive can collect the leaf values.

    Solution

    js
    function flatten(items) {
      const result = [];
    
      for (const item of items) {
        if (Array.isArray(item)) {
          for (const value of flatten(item)) result.push(value);
        } else {
          result.push(item);
        }
      }
    
      return result;
    }
    
    console.log(flatten([1, [2, [3, [4]], 5], [], 6])); // [1, 2, 3, 4, 5, 6]
    Time O(n), n = total number of values and arrays Space O(n + d), d = nesting depth

    Can you explain this in your own words?

    Back to coding practice