Deserialize Nested List Structure
Stacks & QueuesAuto-graded · 17 test casesLast 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
sis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires deserializing a nested bracket notation string into Python's native list structure. This can be approached using either recursive descent parsing or an explicit stack.
Recursive Descent Parsing
We can process the string sequentially with helper functions:
parse_value()checks if the next non-whitespace character is a[. If so, it delegates toparse_list(). Otherwise, it collects contiguous digits and parses them into an integer.parse_list()advances past the opening bracket[, then loops to consume elements separated by commas until encountering the matching closing bracket].
Because Python lists are passed by reference and built dynamically, this naturally models the hierarchy of nested data.
Correctness
- Hierarchy Preservation: Each opening bracket
[initiates a new list context, and every closing bracket]terminates the most recent list context. - Delimiter and Multi-Digit Handling: Whitespace is safely bypassed, multi-digit numbers are parsed completely via contiguous digit checks, and empty lists
[]are handled by checking for an immediate]after opening.
Complexity
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the length of the string
s. Every character is scanned a constant number of times. - Space Complexity: $\mathcal{O}(D)$ auxiliary memory for the recursion stack (or explicit stack), where $D$ is the maximum nesting depth of the list structure. Output construction takes $\mathcal{O}(N)$ space.
Solution Code
def parse_nested_list(s: str) -> list:
i = 0
def skip_whitespace():
nonlocal i
while i < len(s) and s[i].isspace():
i += 1
def parse_value():
nonlocal i
skip_whitespace()
if s[i] == '[':
return parse_list()
start = i
while i < len(s) and s[i].isdigit():
i += 1
return int(s[start:i])
def parse_list():
nonlocal i
i += 1 # skip '['
result = []
skip_whitespace()
if s[i] == ']':
i += 1
return result
while True:
result.append(parse_value())
skip_whitespace()
if s[i] == ']':
i += 1
return result
i += 1 # skip ','
return parse_value()