Audit and Implement Nested Array Flatten

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

During a code review, a teammate submits the following recursive JavaScript helper to flatten arbitrarily nested arrays into a single-level array:

export function flatten(items) {
  const flat = [];

  function visit(node) {
    for (const key in node) {
      const val = node[key];
      if (typeof val === "object") {
        visit(val);
      } else {
        flat.push(val);
      }
    }
  }

  visit(items);
  return flat;
}

In a live review, you are expected to spot where visit breaks (such as null, non-array objects like {} / Date / Map, enumerable custom or prototype keys visited by for...in, sparse array holes, self-referential cycles, and call-stack exhaustion on deeply nested inputs), clarify the desired API contract, and provide a safe iterative replacement with unit tests.

For the automated Python judge, implement the corrected utility flatten(input: List[object]) -> List[object] adhering to these exact rules:

  • Validate that top-level input is a list (raise TypeError otherwise).
  • Unpack nested list elements to any depth from left to right and return a new flat list, leaving input and all inner lists unmodified (even an already-flat input must return a distinct list object).
  • Keep every non-list value intact as a single element—including None, 0, False, "", strings (str), tuples (tuple), and dictionaries (dict), even if a tuple or dictionary contains lists inside it.
  • Allow the same list object to appear multiple times across separate positions (for example, shared = [1, 2]; flatten([shared, [shared]]) produces [1, 2, 1, 2]), while raising ValueError if any list directly or indirectly contains itself (a cycle).
  • Handle deep nesting (up to 10^5 nested lists) without overflowing the call stack.

Examples

Example 1

Input:  input = [10, [20, [30, 40]], [], 50]
Output: [10, 20, 30, 40, 50]

Nested lists at depth 1 and depth 2 are unpacked in left-to-right order, the empty sublist [] contributes nothing, and 50 appears at the end of the new flat list.

Example 2

Input:  input = ["ok", [None, False], {"ids": [1, 2]}, (3, [4])]
Output: ["ok", None, False, {"ids": [1, 2]}, (3, [4])]

Only list instances ([None, False]) are flattened. Strings ("ok"), falsy primitives (None, False), dictionaries ({"ids": [1, 2]}), and tuples ((3, [4])) are treated as atomic values and preserved whole.

Example 3

Input:  input = [[[]], []]
Output: []

Every nested list is empty, so flattening produces a new empty list [].

Constraints

  • 0 <= N <= 10^5, where N is the total number of entries across input and all nested list objects.
  • Maximum list nesting depth D satisfies 0 <= D <= 10^5.
  • Non-list elements may be any Python object (int, float, bool, None, str, tuple, dict, etc.).

Step-by-step walkthrough

  1. Understand the PR review goals and the Python judge

    flatten(input) takes an array that may contain nested arrays to any depth and returns a new flat array preserving left-to-right order: [10, [20, [30, 40]], [], 50] becomes [10, 20, 30, 40, 50].

    As reviewers of the pull request, we have four jobs:

    1. Find the correctness bugs and broken edge cases in the author's code.
    2. Clarify the API contract (what counts as flattenable, and what happens on null, strings, objects, sparse arrays, or cycles).
    3. Recommend improvements for readability, performance, and stack safety.
    4. Provide a revised implementation and the minimal test suite required before approval.

    The automated judge runs a Python port flatten(input: List[object]) -> List[object], where Python list represents JavaScript Array (so None, str, dict, and tuple must stay intact as single elements) and tests nesting up to 100,000 levels deep.

  2. Task 1: Spot the correctness bugs in the PR

    Almost every bug in the PR comes from two JavaScript footguns — typeof val === "object" and for (const key in node) — plus unbounded recursion:

    • null silently disappears: In JavaScript, typeof null === "object" is true (a famous language quirk from 1995). Calling visit(null) runs for (const key in null), which quietly does zero iterations instead of pushing null.
    • Plain objects and built-in objects are corrupted or erased: Plain objects ({a: 1, b: [2]}), Date, Map, Set, and RegExp all have typeof val === "object". Plain objects get torn apart into their property values, while new Date() and new Map() have zero enumerable own keys and vanish completely!
    • for...in walks enumerable string keys and prototypes, not array indices: Any custom property attached to an array (arr.label = 'x') or any enumerable helper added to Array.prototype is visited and pushed into flat.
    • Call-stack overflow on deep or cyclic arrays: Each nested array adds a frame to the JavaScript call stack (the small fixed-size memory region tracking active function calls). Around ~10,000+ nested levels — or immediately on a self-referencing array a = []; a.push(a) — the function crashes with RangeError: Maximum call stack size exceeded.
    Input                          | Buggy PR output           | Expected output
    -------------------------------+---------------------------+----------------------------
    [1, null, 2]                   | [1, 2]       (lost null!) | [1, null, 2]
    [1, {a: 10, b: [20]}, 3]       | [1, 10, 20, 3] (shredded) | [1, {a: 10, b: [20]}, 3]
    [new Date(0), new Map()]       | []           (both lost!) | [Date(0), Map(0)]
    arr = [1, 2]; arr.tag = "hi"   | [1, 2, "hi"] (extra key!) | [1, 2]
    100,000-deep nested array      | RangeError (stack crash)  | flat array
    a = [1]; a.push(a)             | RangeError (infinite rec) | explicit cycle error
    
  3. Task 2: Clarify the API contract

    Before rewriting code in a PR review, align with the author on the exact edge-case contract:

    • What values get flattened? Only true arrays (Array.isArray(v) in JS; isinstance(item, list) in Python). Plain objects, Map/Set, strings, typed arrays, and Python tuple/dict remain atomic elements.
    • How are null, undefined, None, 0, false, and "" handled? Preserved verbatim as ordinary elements.
    • How should sparse JS arrays ([1, , 3]) behave? Match standard Array.prototype.flat: skip empty holes (!(index in arr)), while keeping explicit undefined slots ([1, undefined, 3]).
    • What if top-level input is not an array (for example flatten("abc") or flatten(null))? Throw TypeError immediately instead of splitting a string into characters or returning [].
    • What if an array contains itself (a cycle)? Throw a clear TypeError / ValueError instead of hanging or crashing the call stack.
    • Shallow vs deep copy: Even when input is already flat ([1, 2]), return a new outer array (out !== input), while keeping object elements as shared references (shallow copy, documented clearly).
  4. Task 3: Improve readability, performance, and stack safety

    • Readability: Replace typeof val === "object" with Array.isArray(val) so the code says what it means, and replace for...in with a standard numeric index loop (0 to arr.length - 1).
    • Performance: for...in converts every array index to a string and walks the prototype chain, making it an order of magnitude slower than indexed array access on large arrays.
    • Stack safety: Replace recursive visit(val) calls with an explicit stack array stored on the heap (general program memory, which grows to millions of entries without overflowing the call stack). Even built-in input.flat(Infinity) uses internal recursion in engines like V8 and still throws RangeError at 100,000 levels!
    • Cycle safety without breaking shared references: Track onPath (the set of arrays currently open from the root down to the current element). Removing an array from onPath as soon as we finish reading it allows harmless shared sub-arrays like const x = [1, 2]; flatten([x, x]) while catching true cycles (a.push(a)).
  5. Task 4a: Propose the revised JavaScript implementation

    Here is the clean, stack-safe JavaScript replacement to propose on the PR:

    export function flatten(input) {
      if (!Array.isArray(input)) {
        throw new TypeError("flatten expects an array");
      }
    
      const out = [];
      // Explicit stack of { arr, nextIndex } frames stored on the heap.
      const stack = [{ arr: input, nextIndex: 0 }];
      // Ancestor arrays currently open on our path; seeing one again means a cycle.
      const onPath = new Set([input]);
    
      while (stack.length > 0) {
        const frame = stack[stack.length - 1];
        if (frame.nextIndex === frame.arr.length) {
          stack.pop();
          onPath.delete(frame.arr);
          continue;
        }
    
        const index = frame.nextIndex;
        frame.nextIndex += 1; // advance parent BEFORE descending into any child
    
        if (!(index in frame.arr)) {
          continue; // skip sparse-array holes, matching Array.prototype.flat
        }
    
        const value = frame.arr[index];
        if (Array.isArray(value)) {
          if (onPath.has(value)) {
            throw new TypeError("cannot flatten a cyclic array");
          }
          onPath.add(value);
          stack.push({ arr: value, nextIndex: 0 });
        } else {
          out.push(value);
        }
      }
    
      return out;
    }
    
  6. Task 4b: Write the Python implementation and minimal test checklist

    In Python, list objects are mutable and cannot be placed directly in a set, so active_list_ids stores id(lst) — each list's unique memory identity while it stays alive on stack. Because stack keeps every ancestor list alive until stack.pop(), its id cannot be reused by another object while inside active_list_ids.

    from typing import List, Set, Tuple
    
    
    def flatten(input: List[object]) -> List[object]:
        if not isinstance(input, list):
            raise TypeError("flatten expects a list")
    
        result: List[object] = []
        stack: List[Tuple[List[object], int]] = [(input, 0)]
        active_list_ids: Set[int] = {id(input)}
    
        while stack:
            current_list, index = stack[-1]
            if index == len(current_list):
                stack.pop()
                active_list_ids.remove(id(current_list))
                continue
    
            stack[-1] = (current_list, index + 1)
            item = current_list[index]
    
            if isinstance(item, list):
                if id(item) in active_list_ids:
                    raise ValueError("cannot flatten a list that contains itself")
                active_list_ids.add(id(item))
                stack.append((item, 0))
            else:
                result.append(item)
    
        return result
    

    Minimal test checklist to request before approving the PR:

    • Happy paths and empty cases: [], [[[]], []], [10, [20, [30, 40]], [], 50].
    • Falsy primitives kept: [null, undefined, 0, false, ""] (Python [None, 0, False, ""]).
    • Strings and non-array objects kept whole: ["ok", {ids: [1, 2]}, new Date(0)] (Python ["ok", {"ids": [1, 2]}, (3, [4])]).
    • Immutability and new reference: flatten(flat) returns a new array and leaves input untouched.
    • Shared reference vs cycle: x = [1, 2]; flatten([x, [x]]) -> [1, 2, 1, 2], while a = []; a.push(a) throws.
    • Deep nesting (100,000 levels) and JS-specific sparse arrays / extra array properties / non-array inputs.
  7. Trace Example 1 on the explicit stack

    Let's trace flatten([10, [20, [30, 40]], [], 50]), naming the lists A = [10, B, D, 50], B = [20, C], C = [30, 40], and D = []:

    Step | Stack (bottom -> top)        | Action                         | result
    -----+------------------------------+--------------------------------+--------------------
    start| [(A, 0)]                     | active = {A}                   | []
      1  | [(A, 1)]                     | A[0] = 10 -> append            | [10]
      2  | [(A, 2), (B, 0)]             | A[1] = B (list) -> push (B, 0) | [10]
      3  | [(A, 2), (B, 1)]             | B[0] = 20 -> append            | [10, 20]
      4  | [(A, 2), (B, 2), (C, 0)]     | B[1] = C (list) -> push (C, 0) | [10, 20]
      5  | [(A, 2), (B, 2), (C, 2)]     | C[0]=30, C[1]=40 -> append     | [10, 20, 30, 40]
      6  | [(A, 2)]                     | pop finished C, then pop B     | [10, 20, 30, 40]
      7  | [(A, 3), (D, 0)] -> [(A, 3)] | A[2] = D ([]) -> push & pop D  | [10, 20, 30, 40]
      8  | [(A, 4)] -> []               | A[3] = 50 -> append, pop A     | [10, 20, 30, 40, 50]
    

    Notice how advancing (A, 1) to (A, 2) before pushing (B, 0) acts just like a bookmark: when C and B finish and pop off, A resumes cleanly at index 2 (D = []) and then index 3 (50).

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def flatten(input: List[object]) -> List[object]:
        # Reject non-list top-level inputs explicitly instead of iterating strings or dicts.
        if not isinstance(input, list):
            raise TypeError("flatten expects a list")
    
        # result: new flat list collecting non-list items in left-to-right order
        result: List[object] = []
        # stack: explicit traversal frames of (current_list, next_index), e.g. [(input, 0)]
        stack: List[Tuple[List[object], int]] = [(input, 0)]
        # active_list_ids: object ids of lists currently open on the ancestor path;
        # seeing an active id again means a list contains itself (a cycle).
        active_list_ids: Set[int] = {id(input)}
    
        while stack:
            current_list, index = stack[-1]
    
            # When we reach the end of current_list, close its frame and remove it from
            # active_list_ids so a shared sibling list like [x, x] is allowed later.
            if index == len(current_list):
                stack.pop()
                active_list_ids.remove(id(current_list))
                continue
    
            # Advance the parent's index BEFORE descending into a child list so we
            # resume at index + 1 once that child finishes.
            stack[-1] = (current_list, index + 1)
            item = current_list[index]
    
            if isinstance(item, list):
                if id(item) in active_list_ids:
                    raise ValueError("cannot flatten a list that contains itself")
                active_list_ids.add(id(item))
                stack.append((item, 0))
            else:
                result.append(item)
    
        return result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture nested arrays like folders inside folders on a computer, where you want to list every non-folder item from left to right. A recursive function relies on the language's call stack (a small, fixed-size memory region tracking active function calls) to remember which folder and position to return to, which crashes when folders are nested tens of thousands of levels deep. Instead, we maintain our own explicit bookmark stack on the heap (general program memory), where each entry (current_list, next_index) remembers an open list and the next slot to read inside it.

The PR's implementation fails for three separate reasons. First, checking typeof val === "object" in JavaScript matches null, plain {} objects, Dates, and Maps, so null and Date silently vanish while plain objects get shredded into their values. Second, for (const key in node) iterates enumerable properties (all string-keyed properties marked visible to loops, including custom properties and Array.prototype extensions) rather than numeric array indices. Third, recursive calls blow the call stack on deeply nested or cyclic arrays.

Walk through A = [10, [20, [30, 40]], [], 50] (Example 1, with B = [20, C], C = [30, 40], and D = []) to see how the bookmark stack works:

  1. Start with stack = [(A, 0)] and active_list_ids = {id(A)}. Read A[0] = 10, advance top frame to (A, 1), and append 10 to result = [10].
  2. Read A[1] = B (a list), advance top frame to (A, 2), add id(B) to active_list_ids, and push (B, 0).
  3. Read B[0] = 20 -> result = [10, 20]; read B[1] = C -> push (C, 0); read 30 and 40 -> result = [10, 20, 30, 40]; pop finished C and B; push and immediately pop empty D = [] at A[2]; finally append A[3] = 50 and pop A to return [10, 20, 30, 40, 50].

Complexity

Let N be the total number of list entries across input and all nested sub-lists combined, and let D be the maximum nesting depth.

  • Time: O(N). Every list element and sub-list reference is visited once by advancing index in O(1) time, and each sub-list is pushed, popped, and added/removed in active_list_ids once in O(1) average time.
  • Space: O(D) auxiliary space beyond the output list. At any moment stack and active_list_ids hold only the chain of currently open ancestor lists from the root down to the active element (at most D entries), while result stores the flattened non-list elements.

Edge cases

  • Empty input and nested empty lists ([], [[], [[]]]): Frames hit index == len(current_list) immediately and pop, returning [].
  • Falsy values (None/null/undefined, 0, False, ""): Treated as atomic elements and preserved in order, fixing the PR's typeof null === 'object' bug.
  • Strings ("ab"): Kept intact as single elements; in Python, recursing on arbitrary iterables without excluding str causes infinite recursion because iterating "a" yields "a" again.
  • Plain objects, dicts, tuples, Dates, Maps: Kept whole as single elements because only Array.isArray / isinstance(item, list) triggers flattening.
  • Shared sub-lists vs cycles: If x = [1, 2], [x, [x]] is a directed acyclic graph (a structure that reuses the same sub-list without looping back into an ancestor) and validly flattens to [1, 2, 1, 2] because id(x) leaves active_list_ids when the first x finishes; a true cycle a = []; a.append(a) keeps id(a) active and raises ValueError.
  • Already-flat input ([1, 2]): Still returns a shallow copy (a new outer list referencing the same inner objects) rather than returning input itself, so mutating the output never mutates input.
  • 100,000-level deep nesting: Runs comfortably because heap memory holds 100,000 lightweight tuples without touching the call stack.

Common mistakes

  • Using typeof val === "object" instead of Array.isArray(val): Misclassifies null and non-array objects as arrays.
  • Using for...in on JavaScript arrays: Visits string keys, non-index properties (arr.foo = 1), and enumerable prototype methods, while running much slower than numeric indexing.
  • Using a global visited set for cycle detection: Rejects valid inputs like x = [1, 2]; flatten([x, x]) that reuse the same list object twice side by side; only lists on the current ancestor path indicate a cycle.
  • Comparing lists by value (item in on_path) instead of identity (id(item)): Two separate empty lists [[], []] have equal values ([] == []) even though they are distinct objects, and mutable Python lists cannot be placed directly in a set anyway (sets require immutable keys whose hash value never changes).
  • Pushing all reversed children onto a value stack (stack.extend(reversed(item))): Avoids call-stack overflow, but blows auxiliary space from O(D) up to O(N) on wide sub-lists and loses ancestor boundaries needed to detect cycles.

Alternative approaches

  • Simple recursion (isinstance(item, list) + out.extend(flatten(item))): Easy to read and great as a reference check in unit tests on shallow inputs, but creates intermediate sub-arrays at every level (O(N * D) copying if done with extend per level instead of a shared out list) and crashes past ~1,000 levels in Python or ~10,000 levels in JavaScript.
  • Built-in input.flat(Infinity) in JavaScript: Concise and handles sparse holes properly, so mention it first in a real PR review — while noting that it lacks cycle detection and still overflows the C++ call stack in V8 on extreme depths (100,000 levels).

Follow-up questions

  • How would you extend flatten to accept a maximum nesting limit (like Array.prototype.flat(depth))? Store a 3-tuple (current_list, next_index, current_depth) on stack, starting at (input, 0, 0). Only descend into a child list when isinstance(item, list) and current_depth < depth (pushing (item, 0, current_depth + 1)); once current_depth == depth, append child lists directly to result without flattening further (depth = 0 cleanly returns a shallow copy).
  • If the flattened output could contain millions of elements and callers only inspect the first few, how can you avoid allocating the full result array upfront? Convert flatten into a generator (a function using yield in Python or function* / yield in JavaScript that produces one item at a time on demand). Replacing result.append(item) with yield item drops total memory usage to O(D) regardless of output size and lets callers stop early after taking the first k items.
  • What changes are needed in Python if callers want arbitrary iterables (such as tuples or generators) flattened too, without breaking strings or dictionaries? Check isinstance(item, collections.abc.Iterable) and not isinstance(item, (str, bytes, dict)) — explicitly excluding strings/bytes (which yield 1-character strings forever) and dicts (which would silently drop values and emit keys). Store iter(item) frames on stack and advance them with next(iterator, SENTINEL), noting that unordered iterables like set have no deterministic left-to-right order.

Follow-up questions

Similar questions

More Elastic interview questions

All 2 Elastic questions →