Skip to problem
←

Flatten Nested List Iterator

Medium 0 attempts

You're given a nested list where each entry is either a plain integer or another nested list, which may itself contain integers or further nested lists to any depth. Implement NestedIterator with hasNext() and next() to traverse the integers lazily in left-to-right order. Call next() only when hasNext() is true. The editor drains the iterator into an array for comparison.

Empty nested lists contribute no values. Repeated hasNext() calls must not advance past an integer. The input remains unchanged while the iterator is in use.

Function contract

The constructor receives ordinary JavaScript arrays containing integers or nested arrays, not NestedInteger wrapper objects.

Output: hasNext() returns whether an unread integer remains, without consuming it. next() returns and consumes that integer. The runner drains the iterator and displays the integers as an array.

Example 1

Input
nestedList = [[1,1],2,[1,1]]
Output
[1,1,2,1,1]

Example 2

Input
nestedList = [1,[4,[6]]]
Output
[1,4,6]
Constraints
  • 1 <= nestedList.length <= 500
  • Values are in range [-10^6, 10^6]

Lazy Traversal with List Frames

Keep a stack of lists and their next unread indices. hasNext() skips exhausted lists and descends into nested arrays until an integer is ready. It never consumes that integer, so repeated calls are safe. next() advances past exactly one integer.

The constructor keeps a reference to the input rather than flattening or copying it. Do not modify the input while iterating.

javascript
class NestedIterator {
  constructor(nestedList) {
    this.frames = [{ list: nestedList, index: 0 }];
  }

  hasNext() {
    while (this.frames.length) {
      const frame = this.frames[this.frames.length - 1];
      if (frame.index === frame.list.length) {
        this.frames.pop();
        continue;
      }
      const value = frame.list[frame.index];
      if (typeof value === 'number') return true;
      frame.index++;
      this.frames.push({ list: value, index: 0 });
    }
    return false;
  }

  next() {
    if (!this.hasNext()) return undefined;
    const frame = this.frames[this.frames.length - 1];
    return frame.list[frame.index++];
  }
}

Time: O(1) construction and O(E + C) over a traversal with C method calls, where E counts all integer and nested-list entries. A single call can skip many empty lists, so it is not necessarily O(1) per returned integer.

Space: O(D) auxiliary space, where D is the maximum nesting depth; the input is not copied.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript