Flatten Nested List Iterator

Medium

Topics
StackTreeDFSDesignQueueIterator

You are given a nested list of integers, where each element is either an integer or a list whose elements are themselves integers or lists.

Return all the integers in left-to-right order, with the nesting removed.

LeetCode poses this as an iterator class with next() and hasNext(), built over a NestedInteger interface. The judge here reads a line of text, so the structure arrives as the string s that spells it and the whole flattened sequence is returned at once. The interesting part — producing the integers in order without knowing the depth in advance — is unchanged, and the editorial covers the lazy form the class needs.

Example 1

input[[1,1],2,[1,1]]
answer1011221314
was at the top levelwas inside a nested list
The input nests lists inside lists, here 2 levels deep. The answer is every integer it contains with the brackets discarded, ordered by where it appears reading left to right — shading separates the integers that sat at the top level from the ones that were nested, and the two kinds interleave rather than being grouped. An empty nested list contributes nothing at all.
Depth does not affect position: a deeply nested integer still comes out where its brackets sit in the text.
Input:  s = "[[1,1],2,[1,1]]"
Output: [1,1,2,1,1]
Explanation: The two inner lists are opened in place; nothing is reordered.

Example 2

input[1,[4,[6]]]
answer104162
was at the top levelwas inside a nested list
Input:  s = "[1,[4,[6]]]"
Output: [1,4,6]
Explanation: Nesting can go to any depth.

Example 3

input[[],[3],[]]
answer30
was inside a nested list
Input:  s = "[[],[3],[]]"
Output: [3]
Explanation: Empty lists contribute nothing, and an iterator must not report one as an available element.

Constraints

  • 1 <= number of integers <= 500
  • The nesting depth is at most 50
  • -10^6 <= integer value <= 10^6
Editorial — intuition, approach, complexity and pitfalls

Intuition

Returning everything at once is a plain left-to-right walk: on an integer emit it, on a list recurse into it. That is the whole of the batched problem.

The class form is the one worth thinking about, because hasNext() is harder than it looks. The naive answer — "is there anything left in the current list" — is wrong on example 3: the structure still has elements, but they are empty lists and no integer will ever come out of them. So hasNext() cannot answer without looking ahead past any amount of empty nesting.

The usual resolution is a stack holding positions rather than values. hasNext() advances it past anything that is not an integer — opening lists and discarding exhausted ones — until an integer is on top or the stack empties. next() then just takes it. The work migrates into hasNext(), which is why it is allowed to mutate state.

The other approach is to flatten eagerly in the constructor and hand out a cursor, which is exactly the function here. It is simpler and uses memory proportional to the whole input, which is the trade an iterator is normally built to avoid.

Approach

  1. Parse the bracket string into a nested structure of integers and lists.
  2. Walk it in order: append each integer to the output; for each list, recurse into it before continuing with the next sibling.
  3. An empty list contributes nothing and needs no special case — the recursion simply finds nothing in it.
  4. For the lazy form instead, hold a stack of (list, index) pairs and have hasNext() advance past non-integers until an integer is in front.

Walkthrough

s = "[[],[3],[]]"

element   action                       output
  []      recurse, find nothing        []
  [3]     recurse, emit 3              [3]
  []      recurse, find nothing        [3]

answer [3]

For the iterator form this is the case that matters:
after 3 is taken, two elements remain in the outer list and
hasNext() must still answer false. Counting remaining
ELEMENTS answers true and is wrong.

Complexity

  • Time — O(n): every integer and every bracket is handled once.
  • Space — O(n): the output. The lazy iterator holds a stack as deep as the nesting, which is its advantage.

Common Pitfalls

  • In the iterator form, writing hasNext() as a check on the current list rather than a look-ahead. Example 3 breaks it.
  • Flattening in next() instead of hasNext(). By the time next() is called the caller has already been told an element exists, so the look-ahead has to happen before that promise is made.
  • Reversing the order when pushing a list onto a stack. A stack hands back the last thing pushed, so the elements go on in reverse to come out in order.
  • Treating an empty list as an element worth reporting.

Full Solution — all languages

class Solution:
    def flatten(self, s):
        import json
        data = json.loads(s)
        out = []

        def walk(items):
            for item in items:
                if isinstance(item, list):
                    walk(item)
                else:
                    out.append(item)

        walk(data)
        return out
SensAI
Beta
Tap the mic to stop voice mode