Skip to content
Problem 385 · LeetCode 385(opens in a new tab)

Mini Parser

MediumRecursion

A nested list holds elements that are either whole numbers or other nested lists, to any depth. You get the text form of one such value in a string s, for example [7,[-2,40]] or just -318.

Turn the text back into a NestedInteger object and return it. A NestedInteger holds either a single integer or a list of NestedIntegers. You can build one with NestedInteger() for an empty list or NestedInteger(value) for an integer, and append to a list with add(elem).

Example 1

Input:  s = "[7,[-2,40]]"
Output: [7,[-2,40]]
Why:    a list of 7 and a list holding −2 and 40
2 more examples and the constraints

Example 2

Input:  s = "-318"
Output: -318
Why:    no brackets, so it is a single integer

Example 3

Input:  s = "[[],[5]]"
Output: [[],[5]]
Why:    an empty list is still an element

Constraints

  • 1 ≤ length of s ≤ 50,000
  • s holds only digits, [, ], - and ,
  • s is always a valid serialized value
  • Every integer is between −1,000,000 and 1,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recursive descentO(n)
  2. Stack of open listsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 50,000 charactersVerdict
Recursive descentO(n)
Clear; deep input risks overflow
Stack of open listsO(n)
Best; same pass, no recursion

n = length of s, d = deepest nesting.

Edge cases to test

  • No brackets. "-318" is a single integer, not a list holding it.
  • Empty lists. "[]" and "[[],[5]]" must keep their empty lists as real elements.
  • Negative numbers. The - is part of the number, so start reading at the sign, not at the first digit.
  • Deep nesting. 300 brackets around one 9 should still give the same depth back.

Common mistakes

  • Wrapping a lone integer in a list, so -318 comes back as [-318].
  • Adding a number only on , and losing the last number before a ].
  • Popping the outermost list on the final ] and having nothing left to return.

How to talk through it

  1. 1Clarify. Can numbers be negative or have several digits? Can lists be empty? Is the input always valid?
  2. 2Name the structure. Brackets nest, and each ] closes the newest open list.
  3. 3Sketch the recursion. parse reads one element; a list calls parse for each child.
  4. 4Switch to a stack. Push on [, add numbers to the top, pop on ]; no recursion depth to worry about.
  5. 5Test out loud. Run "-318", "[]", "[[],[5]]" and a number right before a closing bracket.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?