Parse a nested list from a string
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in parsing nested data structures, string processing, hierarchical representation construction, and analysis of algorithmic time and space complexity within the Coding & Algorithms domain.
Constraints
- The input string encodes exactly one valid outer list.
- 2 <= len(s) <= 10^5
- Whitespace may appear anywhere outside of numbers.
- Integers may be negative and may contain multiple digits.
Examples
Input: "[1,2,[3,-4],5]"
Expected Output: [1, 2, [3, -4], 5]
Explanation: The string contains integers at the top level and one nested list.
Input: "[]"
Expected Output: []
Explanation: An empty list should parse to an empty Python list.
Input: "[10,[20,[30]],40]"
Expected Output: [10, [20, [30]], 40]
Explanation: This checks multiple nesting levels with multi-digit values.
Input: "[ -1, 23, [ 0, -999 ], [] ]"
Expected Output: [-1, 23, [0, -999], []]
Explanation: Whitespace should be ignored, negative values should parse correctly, and empty sublists should be preserved.
Input: "[[],[[]],-5,12345]"
Expected Output: [[], [[]], -5, 12345]
Explanation: This tests empty nested lists, a negative number, and a larger multi-digit number.
Input: " [[[1]], 2] "
Expected Output: [[[1]], 2]
Explanation: Leading and trailing whitespace should not affect parsing.
Hints
- Opening and closing brackets suggest using a stack to keep track of the current list being built.
- When you encounter a digit or a minus sign, consume the entire integer before continuing the scan.