Flatten Nested List Iterator
Medium
Topics
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: 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: s = "[1,[4,[6]]]" Output: [1,4,6] Explanation: Nesting can go to any depth.
Example 3
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
- Parse the bracket string into a nested structure of integers and lists.
- Walk it in order: append each integer to the output; for each list, recurse into it before continuing with the next sibling.
- An empty list contributes nothing and needs no special case — the recursion simply finds nothing in it.
- 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 ofhasNext(). By the timenext()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 outimport java.util.*;
class Solution {
public java.util.List<Integer> flatten(String s) {
List<Integer> out = new ArrayList<>();
int i = 0;
while (i < s.length()) {
char c = s.charAt(i);
if (c == '-' || (c >= '0' && c <= '9')) {
int j = (c == '-') ? i + 1 : i;
while (j < s.length() && s.charAt(j) >= '0' && s.charAt(j) <= '9') j++;
out.add(Integer.parseInt(s.substring(i, j)));
i = j;
} else i++;
}
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> flatten(string s) {
// one scan: brackets only change depth, and depth is irrelevant to the
// order, so the integers come out in the order they are read
vector<int> out;
size_t i = 0;
while (i < s.size()) {
char c = s[i];
if (c == '-' || isdigit((unsigned char)c)) {
size_t j = (c == '-') ? i + 1 : i;
while (j < s.size() && isdigit((unsigned char)s[j])) j++;
out.push_back(stoi(s.substr(i, j - i)));
i = j;
} else i++;
}
return out;
}
};/**
* @param {string} s
* @return {number[]}
*/ var flatten = function(s) {
const data = JSON.parse(s);
const out = [];
const walk = (items) => {
for (const item of items) {
if (Array.isArray(item)) walk(item);
else out.push(item);
}
};
walk(data);
return out;
};