Flatten Nested List Iterator
Problem statement
Implement an iterator over a nested list of integers. Each element is either a signed integer or another list. Visit integer leaves in their original left-to-right, depth-first order; an empty list contributes no values.
The string nestedList is a valid JSON serialization of that list. Initialize one iterator and process operations in order:
HAS_NEXTreports whether an integer remains. It must not consume an integer, so repeated checks see the same next value.NEXTreturns the next integer and advances past exactly that occurrence. It may be called without a preceding check; every such call is guaranteed to occur while an integer remains.
Return one string per operation: "true" or "false" for HAS_NEXT, and the returned integer in canonical decimal form for NEXT. Keep duplicate integers and preserve negative values and zero.
The operation sequence may stop before exhaustion. Return only its results. The nested list is immutable, and this exercise has no removal operation.
Function
runNestedIterator(nestedList: String, operations: String[]) → String[]Examples
Example 1
nestedList = "[[1,1],2,[1,1]]"operations = ["HAS_NEXT","HAS_NEXT","NEXT","NEXT","HAS_NEXT","NEXT","NEXT","NEXT","HAS_NEXT"]return = ["true","true","1","1","true","2","1","1","false"]Both initial checks see the same first integer. The five NEXT calls return 1, 1, 2, 1, 1; the last check reports exhaustion.
Example 2
nestedList = "[1,[4,[6]]]"operations = ["NEXT","HAS_NEXT","NEXT","HAS_NEXT","NEXT","HAS_NEXT"]return = ["1","true","4","true","6","false"]The nested list is visited depth first from left to right: 1, then 4, then 6.
Example 3
nestedList = "[[],[7,[]],[]]"operations = ["HAS_NEXT","NEXT","HAS_NEXT","HAS_NEXT"]return = ["true","7","false","false"]Empty subarrays contribute no integers. After 7, both later checks remain false.
Constraints
nestedListis valid JSON containing only arrays and integers; the outermost value is an array with1through500elements.- Integers satisfy
-10^6 <= value <= 10^6. Empty inner arrays and JSON whitespace are allowed. - For this exercise, assume at most
2000integer-or-array nodes, counting the outer array, at most30nested array levels, and at most20000characters innestedList. - For this exercise, assume
1 <= operations.length <= 1000; each operation isHAS_NEXTorNEXT, and everyNEXTis valid at its position.