Flatten Nested List Iterator LeetCode Solution

Last updated on February 2nd, 2025 at 05:34 am

Here, we see a Flatten Nested List Iterator LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Design, Stack

Companies

Facebook, Google, Twitter

Level of Question

Medium

Flatten Nested List Iterator LeetCode Solution

Flatten Nested List Iterator LeetCode Solution

1. Problem Statement

You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.

Implement the NestedIterator class:

  • NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList.
  • int next() Returns the next integer in the nested list.
  • boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.

Your code will be tested with the following pseudocode:initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res

If res matches the expected flattened list, then your code will be judged as correct.

Example 1:
Input: nestedList = [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Example 2:
Input: nestedList = [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].

2. Coding Pattern Used in Solution

The coding pattern used here is “Flattening Nested Structures”. This pattern involves traversing a nested or hierarchical structure (e.g., nested lists, trees) and converting it into a flat, linear structure (e.g., a list of integers). This is achieved using a stack or recursion to manage the traversal.

3. Code Implementation in Different Languages

3.1 Flatten Nested List Iterator C++

class NestedIterator {
public:
    NestedIterator(vector<NestedInteger> &nestedList) {
        begins.push(nestedList.begin());
        ends.push(nestedList.end());
    }
    int next() {
        hasNext();
        return (begins.top()++)->getInteger();
    }
    bool hasNext() {
        while (begins.size()) {
            if (begins.top() == ends.top()) {
                begins.pop();
                ends.pop();
            } else {
                auto x = begins.top();
                if (x->isInteger())
                    return true;
                begins.top()++;
                begins.push(x->getList().begin());
                ends.push(x->getList().end());
            }
        }
        return false;
    }

private:
    stack<vector<NestedInteger>::iterator> begins, ends;
};

3.2 Flatten Nested List Iterator Java

public class NestedIterator implements Iterator<Integer> {
    public NestedIterator(List<NestedInteger> nestedList) {
        lists = new Stack<>();
        lists.push(nestedList.listIterator());
    }
    public Integer next() {
        hasNext();
        return lists.peek().next().getInteger();
    }
    public boolean hasNext() {
        while (!lists.empty()) {
            if (!lists.peek().hasNext()) {
                lists.pop();
            } else {
                NestedInteger x = lists.peek().next();
                if (x.isInteger())
                    return lists.peek().previous() == x;
                lists.push(x.getList().listIterator());
            }
        }
        return false;
    }
    private Stack<ListIterator<NestedInteger>> lists;
}

3.3 Flatten Nested List Iterator JavaScript

var NestedIterator = function(nestedList) {
    this.stack = [];
    this.beepboop(nestedList);
};

NestedIterator.prototype.beepboop = function(nestedList) {
    let n;
    while (n = nestedList.pop()) {
        if (n.isInteger()) this.stack.push(n.getInteger());
        else this.beepboop(n.getList());
    }
};

NestedIterator.prototype.hasNext = function() {
    return !!this.stack.length;
};

NestedIterator.prototype.next = function() {
	return this.stack.pop();
};

3.4 Flatten Nested List Iterator Python

class NestedIterator(object):
    def __init__(self, nestedList):
        self.stack = [[nestedList, 0]]
    def next(self):
        self.hasNext()
        nestedList, i = self.stack[-1]
        self.stack[-1][1] += 1
        return nestedList[i].getInteger()  
    def hasNext(self):
        s = self.stack
        while s:
            nestedList, i = s[-1]
            if i == len(nestedList):
                s.pop()
            else:
                x = nestedList[i]
                if x.isInteger():
                    return True
                s[-1][1] += 1
                s.append([x.getList(), 0])
        return False

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(N)O(D)
JavaO(N)O(D)
JavaScriptO(N)O(N)
PythonO(N)O(D)

where,
N: Total number of integers and lists in the nested structure.
D: Maximum depth of the nested structure.

The code implements a Flattening Nested Structures pattern using stacks or recursion to handle arbitrarily deep nesting. The time complexity is O(N) for all implementations, as every element is visited once. The space complexity varies depending on whether the implementation uses lazy evaluation (O(D)) or pre-flattening (O(N)).

Scroll to Top