FastPrepFlatten Nested List Iterator

Flatten Nested List Iterator

NVIDIA logoNVIDIA● MediumFULLTIMEPHONE SCREEN
Learn

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_NEXT reports whether an integer remains. It must not consume an integer, so repeated checks see the same next value.
  • NEXT returns 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

  • nestedList is valid JSON containing only arrays and integers; the outermost value is an array with 1 through 500 elements.
  • Integers satisfy -10^6 <= value <= 10^6. Empty inner arrays and JSON whitespace are allowed.
  • For this exercise, assume at most 2000 integer-or-array nodes, counting the outer array, at most 30 nested array levels, and at most 20000 characters in nestedList.
  • For this exercise, assume 1 <= operations.length <= 1000; each operation is HAS_NEXT or NEXT, and every NEXT is valid at its position.

More NVIDIA problems

See NVIDIA hiring insights
public String[] runNestedIterator(String nestedList, String[] operations) {
    // Build one nested-list iterator and return each requested operation result.
}
nestedList"[[1,1],2,[1,1]]"
operations["HAS_NEXT","HAS_NEXT","NEXT","NEXT","HAS_NEXT","NEXT","NEXT","NEXT","HAS_NEXT"]
expected["true", "true", "1", "1", "true", "2", "1", "1", "false"]
Checking account…