KatInterview

Deserialize Nested List Structure

Stacks & QueuesAuto-graded · 17 test cases
MediumAuto-gradedStacks & Queuesstacksstringsparsing

Last updated

Parse a string encoding nested lists and non-negative integers into a Python list structure.

Design a function that takes a string representation of a nested list structure and reconstructs it into an equivalent Python list object containing integers and nested lists.

The input string consists of square brackets [ and ], non-negative integers, commas ,, and optional whitespace characters. The structure is guaranteed to be syntactically valid and well-formed.

Constraints

  • The length of string s is between $1$ and $1000$ characters.
  • All numbers in the input are non-negative integers (can be single-digit or multi-digit).
  • The input string is guaranteed to be validly formatted.
  • The root of the input string is always an enclosed list (begins with [ and ends with ]).

Examples

Example 1

Input: parse_nested_list('[1, [2, 3], 4]')

Output: [1, [2, 3], 4]

Example 2

Input: parse_nested_list('[10, [20, [30]]]')

Output: [10, [20, [30]]]

Hints

Hint 1

Use a stack to keep track of currently active nested lists.

Hint 2

When encountering '[', push a new empty list onto the stack and attach it to the current list.

Hint 3

Remember that multi-digit integers require collecting digits until a delimiter like ',', ']', or whitespace is reached.

Hint 4

Be careful with 0; ensure you distinguish between an active zero integer and no integer being processed.