1687. Flatten Below Depth

Medium3.5 points estimatedDepth-First SearchRecursionStack

A file browser shows folders as nested lists: nestedList holds integers (files) and sub-lists (folders) that can nest further. Elements directly in nestedList are at depth 1, elements inside one of its lists are at depth 2, and so on.

Given d, replace every list that sits at depth d with a flat list holding all integers found inside it, at any deeper level, in left-to-right order; sub-lists inside it simply disappear (empty ones contribute nothing, but the flat list itself stays, possibly empty). Lists at depths shallower than d keep their structure, with their contents transformed the same way, and integers are never changed. Return the transformed nested list. Depths up to 50 are fine for plain recursion; the whole pass is O(n) time and O(depth) extra space, where n counts all integers and lists.

Example 1

Input:
nestedList = [1,[2,[3,[4]]],5], d = 2
Output:
[1,[2,[3,4]],5]
Explanation:

The list [3, [4]] sits at depth 2, so it becomes the flat list [3, 4]; everything else is unchanged.

Example 2

Input:
nestedList = [1,[2,[3,[4]]],5], d = 1
Output:
[1,[2,3,4],5]
Explanation:

Every top-level list is flattened, so [2, [3, [4]]] becomes [2, 3, 4].

Example 3

Input:
nestedList = [[],[[],[7],[]],[[1,[]]]], d = 1
Output:
[[],[7],[1]]
Explanation:

[] stays [], [[], [7], []] becomes [7] and [[1, []]] becomes [1].

Constraints

At most 1000 integers and lists in total; nesting depth ≤ 50; 1 ≤ d ≤ 50; -104 ≤ value ≤ 104

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(depth)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…