</>

341. Flatten Nested List Iterator

Medium
Stack Time O(1) Space O(D)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Stack
Time
O(1)
Space
O(D)

Standard Solution (C++)

SummaryGiven a nested list where each element is either an integer or a list of such elements, implement an iterator that yields all integers in left-to-right order across all levels of nesting.

Approach
  • Use a stack initialized with the top-level elements pushed in reverse order so the first element sits on top.
  • hasNext() peeks at the top of the stack: if it is an integer, return true; if it is a list, pop it and push its children in reverse order, then repeat — this lazily flattens one level at a time.
  • next() relies on hasNext() having already ensured the top is a plain integer, then pops and returns it.
  • Each element is pushed and popped at most once, giving amortized O(1) per operation.
#include <vector>
#include <stack>
using namespace std;

// Provided interface — do not implement.
class NestedInteger {
public:
    bool isInteger() const;
    int getInteger() const;
    const vector<NestedInteger>& getList() const;
};

class NestedIterator {
    stack<NestedInteger> st;

    // Push elements of a list onto the stack in reverse so the
    // leftmost element ends up on top.
    void pushReversed(const vector<NestedInteger>& list) {
        for (int i = (int)list.size() - 1; i >= 0; --i)
            st.push(list[i]);
    }

public:
    NestedIterator(vector<NestedInteger>& nestedList) {
        pushReversed(nestedList);
    }

    // Flatten lazily: keep expanding lists on top until an integer surfaces.
    bool hasNext() {
        while (!st.empty()) {
            if (st.top().isInteger()) return true;
            // Top is a list — expand one level.
            vector<NestedInteger> sublist = st.top().getList();
            st.pop();
            pushReversed(sublist);
        }
        return false;
    }

    // Caller must invoke hasNext() before next().
    int next() {
        int val = st.top().getInteger();
        st.pop();
        return val;
    }
};

/**
 * Usage:
 *   NestedIterator it(nestedList);
 *   while (it.hasNext()) cout << it.next() << " ";
 */
Time O(1) amortized per next() / hasNext() call; O(n) total over all n integers Space O(n) where n is the total number of elements (integers and lists) — all top-level elements can reside on the stack simultaneously in the worst case

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

// This is the interface that allows for creating nested lists.
// You should not implement it, or speculate about its implementation
class NestedInteger {
  public:
    // Return true if this NestedInteger holds a single integer, rather than a nested list.
    bool isInteger() const;
    // Return the single integer that this NestedInteger holds, if it holds a single integer
    // The result is undefined if this NestedInteger holds a nested list
    int getInteger() const;
    // Return the nested list that this NestedInteger holds, if it holds a nested list
    // The result is undefined if this NestedInteger holds a single integer
    const vector<NestedInteger> &getList() const;
};


#include <vector>
#include <stack>
using namespace std;

class NestedIterator {
private:
    stack<NestedInteger> st;

public:
    NestedIterator(vector<NestedInteger> &nestedList) {
        for(int i=nestedList.size()-1; i>=0; --i){
            st.push(nestedList[i]);
        }
    }
    
    int next() {
        int top=st.top().getInteger();
        st.pop();
        return top;
    }
    
    bool hasNext() {
       while(!st.empty()){
            NestedInteger cur=st.top();
            if(cur.isInteger()){
                return true;
            }

            // if not
            st.pop();
            vector<NestedInteger> curList=cur.getList();
            for(int i=curList.size()-1; i>=0; --i){
                st.push(curList[i]);
            }
       }
       return false;
    }
};

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i(nestedList);
 * while (i.hasNext()) cout << i.next();
 */

 // Time Complexity: O(1) amortized for next() and hasNext()
 // Space Complexity: O(D) where D is the maximum depth of the nested list

 // Another possible approach is dfs (to flatten the entire list in the constructor)
 // but that would use O(N) space where N is the total number of integers in the nested list.
Time O(1) Space O(D)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern