Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserializedNestedInteger.
Each element is either an integer or a list whose elements may also be integers or other lists.
Example 1:
Input: s = "324"
Output: 324
Explanation: You should return a NestedInteger object which contains a single integer 324.
Example 2:
Input: s = "[123,[456,[789]]]"
Output: [123,[456,[789]]]
Explanation: Return a NestedInteger object containing a nested list with 2 elements:
1. An integer containing value 123.
2. A nested list containing two elements:
i. An integer containing value 456.
ii. A nested list with one element:
a. An integer containing value 789
Constraints:
1 <= s.length <= 5 * 104
s consists of digits, square brackets "[]", negative sign '-', and commas ','.
s is the serialization of valid NestedInteger.
All the values in the input are in the range [-106, 106].
Problem summary: Given a string s 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Stack
Example 1
"324"
Example 2
"[123,[456,[789]]]"
Related Problems
Flatten Nested List Iterator (flatten-nested-list-iterator)
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #385: Mini Parser
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
* // Constructor initializes an empty nested list.
* public NestedInteger();
*
* // Constructor initializes a single integer.
* public NestedInteger(int value);
*
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger holds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // Set this NestedInteger to hold a single integer.
* public void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* public void add(NestedInteger ni);
*
* // @return the nested list that this NestedInteger holds, if it holds a nested list
* // Return empty list if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
class Solution {
public NestedInteger deserialize(String s) {
if ("".equals(s) || "[]".equals(s)) {
return new NestedInteger();
}
if (s.charAt(0) != '[') {
return new NestedInteger(Integer.parseInt(s));
}
NestedInteger ans = new NestedInteger();
int depth = 0;
for (int i = 1, j = 1; i < s.length(); ++i) {
if (depth == 0 && (s.charAt(i) == ',' || i == s.length() - 1)) {
ans.add(deserialize(s.substring(j, i)));
j = i + 1;
} else if (s.charAt(i) == '[') {
++depth;
} else if (s.charAt(i) == ']') {
--depth;
}
}
return ans;
}
}
// Accepted solution for LeetCode #385: Mini Parser
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* type NestedInteger struct {
* }
*
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* func (n NestedInteger) IsInteger() bool {}
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* // So before calling this method, you should have a check
* func (n NestedInteger) GetInteger() int {}
*
* // Set this NestedInteger to hold a single integer.
* func (n *NestedInteger) SetInteger(value int) {}
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* func (n *NestedInteger) Add(elem NestedInteger) {}
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The list length is zero if this NestedInteger holds a single integer
* // You can access NestedInteger's List element directly if you want to modify it
* func (n NestedInteger) GetList() []*NestedInteger {}
*/
func deserialize(s string) *NestedInteger {
ans := &NestedInteger{}
if s == "" || s == "[]" {
return ans
}
if s[0] != '[' {
v, _ := strconv.Atoi(s)
ans.SetInteger(v)
return ans
}
depth := 0
for i, j := 1, 1; i < len(s); i++ {
if depth == 0 && (s[i] == ',' || i == len(s)-1) {
(*ans).Add(*deserialize(s[j:i]))
j = i + 1
} else if s[i] == '[' {
depth++
} else if s[i] == ']' {
depth--
}
}
return ans
}
# Accepted solution for LeetCode #385: Mini Parser
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
# class NestedInteger:
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single integer equal to value.
# """
#
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def add(self, elem):
# """
# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
# :rtype void
# """
#
# def setInteger(self, value):
# """
# Set this NestedInteger to hold a single integer equal to value.
# :rtype void
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class Solution:
def deserialize(self, s: str) -> NestedInteger:
if not s or s == '[]':
return NestedInteger()
if s[0] != '[':
return NestedInteger(int(s))
ans = NestedInteger()
depth, j = 0, 1
for i in range(1, len(s)):
if depth == 0 and (s[i] == ',' or i == len(s) - 1):
ans.add(self.deserialize(s[j:i]))
j = i + 1
elif s[i] == '[':
depth += 1
elif s[i] == ']':
depth -= 1
return ans
// Accepted solution for LeetCode #385: Mini Parser
struct Solution;
use rustgym_util::*;
impl Solution {
fn deserialize(s: String) -> NestedInteger {
nested_integer!(s)
}
}
#[test]
fn test() {
let s = "324".to_string();
let res = nested_integer!("324");
assert_eq!(Solution::deserialize(s), res);
let s = "[123,[456,[789]]]".to_string();
let res = nested_integer!("[123,[456,[789]]]");
assert_eq!(Solution::deserialize(s), res);
let s = "[123,456,[788,799,833],[[]],10,[]]".to_string();
let res = nested_integer!("[123,456,[788,799,833],[[]],10,[]]");
assert_eq!(Solution::deserialize(s), res);
}
// Accepted solution for LeetCode #385: Mini Parser
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* If value is provided, then it holds a single integer
* Otherwise it holds an empty nested list
* constructor(value?: number) {
* ...
* };
*
* Return true if this NestedInteger holds a single integer, rather than a nested list.
* isInteger(): boolean {
* ...
* };
*
* Return the single integer that this NestedInteger holds, if it holds a single integer
* Return null if this NestedInteger holds a nested list
* getInteger(): number | null {
* ...
* };
*
* Set this NestedInteger to hold a single integer equal to value.
* setInteger(value: number) {
* ...
* };
*
* Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
* add(elem: NestedInteger) {
* ...
* };
*
* Return the nested list that this NestedInteger holds,
* or an empty list if this NestedInteger holds a single integer
* getList(): NestedInteger[] {
* ...
* };
* };
*/
function deserialize(s: string): NestedInteger {
if (s === '' || s === '[]') {
return new NestedInteger();
}
if (s[0] !== '[') {
return new NestedInteger(+s);
}
const ans: NestedInteger = new NestedInteger();
let depth = 0;
for (let i = 1, j = 1; i < s.length; ++i) {
if (depth === 0 && (s[i] === ',' || i === s.length - 1)) {
ans.add(deserialize(s.slice(j, i)));
j = i + 1;
} else if (s[i] === '[') {
++depth;
} else if (s[i] === ']') {
--depth;
}
}
return ans;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(n)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
MONOTONIC STACK
O(n) time
O(n) space
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Shortcut: Each element pushed once + popped once → O(n) amortized. The inner while-loop does not make it O(n²).
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Breaking monotonic invariant
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.