Mini Parser - Problem

Given a string s that represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger.

Each element is either an integer or a list whose elements may also be integers or other lists.

The format follows these rules:

  • An integer is just a number (positive, negative, or zero)
  • A list starts with [ and ends with ]
  • Elements in a list are separated by commas
  • Lists can be nested to any depth

Examples:

  • "324" → single integer 324
  • "[123,456]" → list containing two integers
  • "[123,[456,789]]" → list containing an integer and a nested list

Input & Output

Example 1 — Single Integer
$ Input: s = "324"
Output: 324
💡 Note: The input represents a single integer, so we parse and return the number 324.
Example 2 — Simple List
$ Input: s = "[123,456]"
Output: [123,456]
💡 Note: The input represents a list with two integers. We parse the brackets and comma-separated values to return [123,456].
Example 3 — Nested List
$ Input: s = "[123,[456,789]]"
Output: [123,[456,789]]
💡 Note: The input has a nested structure: a list containing an integer (123) and another list ([456,789]). We parse recursively to maintain the nesting.

Constraints

  • 1 ≤ s.length ≤ 5 × 104
  • s consists of digits, square brackets "[]", minus sign "-", and commas ","
  • s is the valid serialization of a NestedInteger
  • All integers in s are in the range [-106, 106]

Visualization

Tap to expand
Mini Parser - Optimal Solution INPUT Input String s: "324" Character Analysis: 3 digit 2 digit 4 digit Type Detection: No '[' found --> Pure Integer s = "324" ALGORITHM STEPS 1 Check First Char Is s[0] == '[' ? NO - not a list 2 Parse as Integer Convert string to int parseInt("324") 3 Create NestedInteger Wrap value in object NestedInteger(324) 4 Return Result Return the integer return 324 Decision Tree: if (s[0] != '[') return parseInt(s) // else parse as list FINAL RESULT Deserialized NestedInteger: 324 INTEGER TYPE Structure View: NestedInteger { value: 324 } Output: 324 OK Key Insight: The parser first checks if the input starts with '['. If not, the entire string is a simple integer. For nested lists, use a stack-based approach: push new NestedInteger on '[', pop and add on ']'. Time Complexity: O(n) | Space Complexity: O(n) for nested cases, O(1) for simple integers TutorialsPoint - Mini Parser | Optimal Solution
Asked in
Facebook 35 Google 28 Amazon 22 Microsoft 18
32.2K Views
Medium Frequency
~25 min Avg. Time
896 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen