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
inputis alist(raiseTypeErrorotherwise). - Unpack nested
listelements to any depth from left to right and return a new flatlist, leavinginputand all inner lists unmodified (even an already-flatinputmust return a distinct list object). - Keep every non-
listvalue intact as a single element—includingNone,0,False,"", strings (str), tuples (tuple), and dictionaries (dict), even if a tuple or dictionary contains lists inside it. - Allow the same
listobject to appear multiple times across separate positions (for example,shared = [1, 2]; flatten([shared, [shared]])produces[1, 2, 1, 2]), while raisingValueErrorif any list directly or indirectly contains itself (a cycle). - Handle deep nesting (up to
10^5nested 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, whereNis the total number of entries acrossinputand all nestedlistobjects.- Maximum list nesting depth
Dsatisfies0 <= D <= 10^5. - Non-list elements may be any Python object (
int,float,bool,None,str,tuple,dict, etc.).
Step-by-step walkthrough
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:
- Find the correctness bugs and broken edge cases in the author's code.
- Clarify the API contract (what counts as flattenable, and what happens on
null, strings, objects, sparse arrays, or cycles). - Recommend improvements for readability, performance, and stack safety.
- 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 Pythonlistrepresents JavaScriptArray(soNone,str,dict, andtuplemust stay intact as single elements) and tests nesting up to100,000levels deep.Task 1: Spot the correctness bugs in the PR
Almost every bug in the PR comes from two JavaScript footguns —
typeof val === "object"andfor (const key in node)— plus unbounded recursion:nullsilently disappears: In JavaScript,typeof null === "object"istrue(a famous language quirk from 1995). Callingvisit(null)runsfor (const key in null), which quietly does zero iterations instead of pushingnull.- Plain objects and built-in objects are corrupted or erased: Plain objects (
{a: 1, b: [2]}),Date,Map,Set, andRegExpall havetypeof val === "object". Plain objects get torn apart into their property values, whilenew Date()andnew Map()have zero enumerable own keys and vanish completely! for...inwalks enumerable string keys and prototypes, not array indices: Any custom property attached to an array (arr.label = 'x') or any enumerable helper added toArray.prototypeis visited and pushed intoflat.- 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 withRangeError: 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 errorTask 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 Pythontuple/dictremain 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 standardArray.prototype.flat: skip empty holes (!(index in arr)), while keeping explicitundefinedslots ([1, undefined, 3]). - What if top-level
inputis not an array (for exampleflatten("abc")orflatten(null))? ThrowTypeErrorimmediately instead of splitting a string into characters or returning[]. - What if an array contains itself (a cycle)? Throw a clear
TypeError/ValueErrorinstead of hanging or crashing the call stack. - Shallow vs deep copy: Even when
inputis already flat ([1, 2]), return a new outer array (out !== input), while keeping object elements as shared references (shallow copy, documented clearly).
- What values get flattened? Only true arrays (
Task 3: Improve readability, performance, and stack safety
- Readability: Replace
typeof val === "object"withArray.isArray(val)so the code says what it means, and replacefor...inwith a standard numeric index loop (0toarr.length - 1). - Performance:
for...inconverts 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 explicitstackarray stored on the heap (general program memory, which grows to millions of entries without overflowing the call stack). Even built-ininput.flat(Infinity)uses internal recursion in engines like V8 and still throwsRangeErrorat100,000levels! - 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 fromonPathas soon as we finish reading it allows harmless shared sub-arrays likeconst x = [1, 2]; flatten([x, x])while catching true cycles (a.push(a)).
- Readability: Replace
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; }Task 4b: Write the Python implementation and minimal test checklist
In Python,
listobjects are mutable and cannot be placed directly in aset, soactive_list_idsstoresid(lst)— each list's unique memory identity while it stays alive onstack. Becausestackkeeps every ancestor list alive untilstack.pop(), itsidcannot be reused by another object while insideactive_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 resultMinimal 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 leavesinputuntouched. - Shared reference vs cycle:
x = [1, 2]; flatten([x, [x]]) -> [1, 2, 1, 2], whilea = []; a.push(a)throws. - Deep nesting (
100,000levels) and JS-specific sparse arrays / extra array properties / non-array inputs.
- Happy paths and empty cases:
Trace Example 1 on the explicit stack
Let's trace
flatten([10, [20, [30, 40]], [], 50]), naming the listsA = [10, B, D, 50],B = [20, C],C = [30, 40], andD = []: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: whenCandBfinish and pop off,Aresumes cleanly at index2(D = []) and then index3(50).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:
- Start with
stack = [(A, 0)]andactive_list_ids = {id(A)}. ReadA[0] = 10, advance top frame to(A, 1), and append10toresult = [10]. - Read
A[1] = B(a list), advance top frame to(A, 2), addid(B)toactive_list_ids, and push(B, 0). - Read
B[0] = 20->result = [10, 20]; readB[1] = C-> push(C, 0); read30and40->result = [10, 20, 30, 40]; pop finishedCandB; push and immediately pop emptyD = []atA[2]; finally appendA[3] = 50and popAto 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 advancingindexinO(1)time, and each sub-list is pushed, popped, and added/removed inactive_list_idsonce inO(1)average time. - Space:
O(D)auxiliary space beyond the output list. At any momentstackandactive_list_idshold only the chain of currently open ancestor lists from the root down to the active element (at mostDentries), whileresultstores the flattened non-list elements.
Edge cases
- Empty input and nested empty lists (
[],[[], [[]]]): Frames hitindex == 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'stypeof null === 'object'bug. - Strings (
"ab"): Kept intact as single elements; in Python, recursing on arbitrary iterables without excludingstrcauses 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]becauseid(x)leavesactive_list_idswhen the firstxfinishes; a true cyclea = []; a.append(a)keepsid(a)active and raisesValueError. - Already-flat input (
[1, 2]): Still returns a shallow copy (a new outer list referencing the same inner objects) rather than returninginputitself, so mutating the output never mutatesinput. - 100,000-level deep nesting: Runs comfortably because heap memory holds
100,000lightweight tuples without touching the call stack.
Common mistakes
- Using
typeof val === "object"instead ofArray.isArray(val): Misclassifiesnulland non-array objects as arrays. - Using
for...inon 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
visitedset for cycle detection: Rejects valid inputs likex = [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 asetanyway (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 fromO(D)up toO(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 withextendper level instead of a sharedoutlist) 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,000levels).
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)onstack, starting at(input, 0, 0). Only descend into a child list whenisinstance(item, list) and current_depth < depth(pushing(item, 0, current_depth + 1)); oncecurrent_depth == depth, append child lists directly toresultwithout flattening further (depth = 0cleanly 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
flatteninto a generator (a function usingyieldin Python orfunction*/yieldin JavaScript that produces one item at a time on demand). Replacingresult.append(item)withyield itemdrops total memory usage toO(D)regardless of output size and lets callers stop early after taking the firstkitems. - 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). Storeiter(item)frames onstackand advance them withnext(iterator, SENTINEL), noting that unordered iterables likesethave no deterministic left-to-right order.
Follow-up questions
- How would you extend flatten to accept a maximum nesting limit (like Array.prototype.flat(depth))?
- 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?
- What changes are needed in Python if callers want arbitrary iterables (such as tuples or generators) flattened too, without breaking strings or dictionaries?
Similar questions
- Real-Time Log Category Aggregator Component in React
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager