288. Flatten Nested List Iterator
You are given a nested list of integers: each element is either a plain integer or another list whose elements are again integers or lists, nested arbitrarily deep.
Every element arrives as a NestedItem helper object (already defined in the starter). Ask it whether it is an integer or a sub-list, then read its stored value or its children accordingly. Your function receives the top-level list of NestedItems and must return a flat list of all the integers in the structure, in exactly the order they appear when the original list is read left to right — a depth-first walk.
This is the classic "design an iterator over a nested list" task: an iterator's next() / hasNext() machinery is precisely an explicit stack that produces this sequence one value at a time.
Example 1:
Input: nestedList = [[1,1],2,[1,1]]
Output: [1, 1, 2, 1, 1]
Explanation: Reading left to right: the first sub-list contributes 1, 1, then the bare 2, then the last sub-list contributes 1, 1.
Example 2:
Input: nestedList = [1,[4,[6]]]
Output: [1, 4, 6]
Explanation: Depth is irrelevant to the order — 6 sits two levels deep but is still visited after 4.
Constraints:
- 1 ≤ total number of integers and sub-lists ≤ 10⁴
- -10⁶ ≤ each integer ≤ 10⁶
- Nesting depth ≤ 50
- The answer order is fixed: the left-to-right reading order of the original structure.
Hints:
The structure is recursive, so recursion fits naturally: for each item, either emit its integer or recurse into its children.
For the iterator version you cannot sit inside a recursive call between next() calls. Simulate the recursion with your own stack: push the top-level items in reverse, then each pop either emits an integer or pushes that sub-list's children (again in reverse).
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: nestedList = [[1,1],2,[1,1]]
Expected output: [1, 1, 2, 1, 1]