KatInterview

341. Flatten Nested List Iterator

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Stack for Lazy Iteration

This problem requires implementing an iterator over a nested data structure. A key consideration for iterators is lazy evaluation: doing just enough work to produce the next item, rather than processing the entire dataset upfront. This is more memory-efficient and faster for partial traversals.

Solution

Flatten Nested List Iterator in Python

# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
#    def isInteger(self) -> bool:
#        """
#        @return True if this NestedInteger holds a single integer, rather than a nested list.
#        """
#
#    def getInteger(self) -> int:
#        """
#        @return the single integer that this NestedInteger holds, if it holds a single integer
#        Return None if this NestedInteger holds a nested list
#        """
#
#    def getList(self) -> [NestedInteger]:
#        """
#        @return the nested list that this NestedInteger holds, if it holds a nested list
#        Return None if this NestedInteger holds a single integer
#        """

class NestedIterator:
    def __init__(self, nestedList: [NestedInteger]):
        # The stack will store NestedInteger objects.
        # We initialize it with a reversed copy of nestedList to process from left to right.
        self.stack = nestedList[::-1]
    
    def next(self) -> int:
        # Per the problem contract, hasNext() is called before next(),
        # ensuring the stack's top is an integer.
        return self.stack.pop().getInteger()
    
    def hasNext(self) -> bool:
        # Loop to ensure the top of the stack is an integer.
        while self.stack:
            top = self.stack[-1]
            if top.isInteger():
                return True
            
            # If top is a list, pop it and push its elements in reverse order.
            self.stack.pop()
            nested_list = top.getList()
            for i in range(len(nested_list) - 1, -1, -1):
                self.stack.append(nested_list[i])
        
        # If stack becomes empty, no more integers are available.
        return False

# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())

Flatten Nested List Iterator in Java

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *
 *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds, if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     // Return empty list if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
import java.util.Deque;
import java.util.ArrayDeque;

public class NestedIterator implements Iterator<Integer> {

    // Use a Deque as a stack to store NestedInteger objects.
    private Deque<NestedInteger> stack;

    public NestedIterator(List<NestedInteger> nestedList) {
        stack = new ArrayDeque<>();
        // Push elements onto the stack in reverse order to process from left to right.
        for (int i = nestedList.size() - 1; i >= 0; i--) {
            stack.push(nestedList.get(i));
        }
    }

    @Override
    public Integer next() {
        // As per the problem contract, hasNext() is called before next(),
        // which guarantees the stack top is an integer.
        return stack.pop().getInteger();
    }

    @Override
    public boolean hasNext() {
        // Ensure the top of the stack is an integer.
        while (!stack.isEmpty()) {
            if (stack.peek().isInteger()) {
                return true;
            }
            // If the top is a list, pop it and flatten its contents onto the stack.
            List<NestedInteger> nestedList = stack.pop().getList();
            // Push its elements in reverse order to maintain the correct sequence.
            for (int i = nestedList.size() - 1; i >= 0; i--) {
                stack.push(nestedList.get(i));
            }
        }
        return false;
    }
}

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i = new NestedIterator(nestedList);
 * while (i.hasNext()) v[f()] = i.next();
 */

Flatten Nested List Iterator in 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 <stack>

class NestedIterator {
private:
    std::stack<NestedInteger> s;

public:
    NestedIterator(vector<NestedInteger> &nestedList) {
        // Push elements from the end to the start onto the stack.
        // This ensures the first element of the list is at the top of the stack.
        for (int i = nestedList.size() - 1; i >= 0; --i) {
            s.push(nestedList[i]);
        }
    }
    
    int next() {
        // hasNext() ensures the top is an integer, so we can safely get it.
        NestedInteger top = s.top();
        s.pop();
        return top.getInteger();
    }
    
    bool hasNext() {
        // Loop until the top of the stack is an integer or the stack is empty.
        while (!s.empty()) {
            NestedInteger top = s.top();
            if (top.isInteger()) {
                return true;
            }
            // If it's a list, pop it and push its elements onto the stack.
            s.pop();
            const vector<NestedInteger> &nested = top.getList();
            // Push list elements in reverse order to maintain original sequence.
            for (int i = nested.size() - 1; i >= 0; --i) {
                s.push(nested[i]);
            }
        }
        // If the stack becomes empty, there are no more integers.
        return false;
    }
};

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

Flatten Nested List Iterator in TypeScript

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * class NestedInteger {
 *     If value is provided, then it holds a single integer
 *     Otherwise it holds an empty nested list
 *     constructor(value?: number) {
 *         ...
 *     };
 *
 *     Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     isInteger(): boolean {
 *         ...
 *     };
 *
 *     Return the single integer that this NestedInteger holds, if it holds a single integer
 *     Return null if this NestedInteger holds a nested list
 *     getInteger(): number | null {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a single integer equal to value.
 *     setInteger(value: number) {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
 *     add(elem: NestedInteger) {
 *         ...
 *     };
 *
 *     Return the nested list that this NestedInteger holds,
 *     or an empty list if this NestedInteger holds a single integer
 *     getList(): NestedInteger[] {
 *         ...
 *     };
 * };
 */

class NestedIterator {
    private stack: NestedInteger[];

    constructor(nestedList: NestedInteger[]) {
        this.stack = [];
        // Push elements from the end to the start onto the stack.
        // This ensures the first element of the list is at the top of the stack.
        for (let i = nestedList.length - 1; i >= 0; i--) {
            this.stack.push(nestedList[i]);
        }
    }

    hasNext(): boolean {
        // Loop until the top of the stack is an integer or the stack is empty.
        while (this.stack.length > 0) {
            const top = this.stack[this.stack.length - 1];
            if (top.isInteger()) {
                return true;
            }

            // If it's a list, pop it and push its elements onto the stack.
            // Non-null assertion `!` is safe because we checked stack.length > 0.
            const list = this.stack.pop()!.getList();

            // Push list elements in reverse order to maintain original sequence.
            for (let i = list.length - 1; i >= 0; i--) {
                this.stack.push(list[i]);
            }
        }
        // If the stack becomes empty, there are no more integers.
        return false;
    }

	next(): number {
        // Per contract, hasNext() is called before next(), ensuring the top is an integer.
        // Non-null assertions `!` are safe due to this contract.
		return this.stack.pop()!.getInteger()!;
    }
}

/**
 * Your ParkingSystem object will be instantiated and called as such:
 * var obj = new NestedIterator(nestedList)
 * var a: number[] = []
 * while (obj.hasNext()) a.push(obj.next());
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.