Python 0385.py
class Solution:
def deserialize(self, s: str) -> NestedInteger:
# strings without any brackets
if s[0] != "[":
return NestedInteger(int(s))
deeper = []
num = "" # current numeric sequence
for c in s:
if c in "-0123456789":
num += c
elif c == "[":
deeper.append(NestedInteger())
else: # "," or "]"
if num:
deeper[-1].add(NestedInteger(int(num)))
num = ""
if c == "]":
# merge with parent
nested = deeper.pop()
if not deeper:
return nested # final bracket
deeper[-1].add(nested)
Difficulty
and has an acceptance rate of about 43% (100k+ submissions).
Typical patterns to solve this problem:
- Depth First Search
- Stack
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided deserialize method converts a string representation of a nested integer list into a NestedInteger object. It distinguishes between a plain integer and a list, then walks through the characters of the string once, building numbers on the fly and using a stack-like structure to assemble nested objects. The algorithm gracefully handles negative numbers, multi-digit values, and empty lists.
Handling a Simple Integer
The first conditional checks whether the input begins with a left bracket. If it does not, the entire string is interpreted as a single integer and wrapped in a NestedInteger instance.
if s[0] != "[":
return NestedInteger(int(s))
This branch covers inputs such as "123" or "-45" and bypasses the more complex parsing logic.
Preparing the Parsing State
Two variables are created before the main loop. deeper is a list that functions as a stack, storing partially built NestedInteger objects for each open bracket encountered. num accumulates characters that form the current numeric token.
deeper = []
num = "" # current numeric sequence
Iterating Over the Characters
The core of the method is a for loop that examines each character c in the input string.
for c in s:
if c in "-0123456789":
num += c
elif c == "[":
deeper.append(NestedInteger())
else: # "," or "]"
if num:
deeper[-1].add(NestedInteger(int(num)))
num = ""
if c == "]":
nested = deeper.pop()
if not deeper:
return nested # final bracket
deeper[-1].add(nested)
Building Numbers
When the character belongs to the set "-0123456789", it is appended to num. This allows the parser to collect digits and an optional leading minus sign, supporting any integer magnitude that fits Python’s int.
Opening a New List
Encountering '[' signals the start of a deeper nesting level. A fresh, empty NestedInteger is pushed onto deeper. This object will later receive its child elements.
Closing a List or Encountering a Separator
Both commas and closing brackets trigger the same block because they delimit the end of a numeric token. If num is non-empty, the accumulated integer is converted, wrapped in a NestedInteger, and added to the most recent container (deeper[-1]). The num buffer is then cleared for the next token.
If the character is a closing bracket ']', the most recent container is popped from the stack, becoming a complete nested structure. When the stack becomes empty after the pop, the method returns this structure as the final result. Otherwise, the completed nested object is added to its parent container, which resides now at the top of the stack.
Edge Cases Managed by the Code
The implementation correctly processes negative numbers because the minus sign is treated as part of the numeric token. Multi-digit numbers are assembled by repeatedly appending digit characters to num. Empty lists such as "[]" are handled: an empty NestedInteger is created when '[' is seen, and upon encountering the matching ']' the stack empties, causing the empty container to be returned. Nested empty lists like "[[],[[]]]" are also supported because each '[' pushes a new container and each ']' merges it back into its parent.
Performance Optimizations Observed
The algorithm operates in a single linear pass over the input string, avoiding any backtracking or repeated scanning. The use of a Python list as a stack (deeper) provides O(1) push and pop operations, ensuring that nesting depth does not degrade performance. The numeric buffer num is reused throughout the loop, eliminating the need for temporary string objects for each digit. Early termination occurs as soon as the outermost list is closed, returning the result without processing any remaining characters (though in a well-formed input there are none). These choices keep the runtime overhead minimal and memory usage proportional to the nesting depth rather than the total number of characters.
ELI5 - Simplified Explanation
Imagine a big box that can hold smaller boxes inside of it. Some boxes might hold just a single number, like a toy, while others might hold more boxes. This code acts like a helper who opens up a long string of characters to build these boxes in exactly the right way.
First, the helper looks at the very beginning of the string. If there are no brackets, it knows there is only one piece of information, so it just turns that into a single number box.
If there are brackets, the helper starts a list to keep track of the boxes being built. Whenever it finds a bracket that opens, it starts a brand new, empty box and puts it on a shelf. When it finds numbers, it collects them together until it has the whole number ready.
When the helper finds a comma or a closing bracket, it knows the current number is finished. It takes that number and puts it into the box that is currently being worked on. If it finds a closing bracket, it means the current box is finished being filled. It takes that box off the shelf and places it inside the bigger box that was holding it before. It keeps doing this until every number is tucked safely into the correct box.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | Python | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| XiaotaoGuo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | Python | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| XiaotaoGuo | C++ |
Videos
Similar Problems
- problem 341: Flatten Nested List Iterator
- problem 722: Remove Comments
Solved On The Same Day
- problem 1913: Maximum Product Difference Between Two Pairs
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality