#385
Mini Parser
MediumStringStackDepth-First SearchStackRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a stack to manage the current context of nested lists and integers. This approach efficiently builds the NestedInteger structure in a single pass through the string.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a stack to keep track of NestedInteger objects and a variable to hold the current number.
- 2Step 2: Iterate through the string character by character. If a digit or negative sign is found, build the current number.
- 3Step 3: On encountering '[', push a new NestedInteger onto the stack.
- 4Step 4: On encountering ']', pop the top NestedInteger from the stack and add it to the last NestedInteger on the stack.
- 5Step 5: On encountering a ',', if there's a number, add it to the current NestedInteger.
solution.py42 lines
1class NestedInteger:
2 def __init__(self, value=None):
3 self.value = value
4 self.is_integer = value is not None
5 self.list = [] if value is None else None
6
7 def add(self, ni):
8 self.list.append(ni)
9
10 def setInteger(self, value):
11 self.value = value
12 self.is_integer = True
13
14 def getInteger(self):
15 return self.value
16
17 def getList(self):
18 return self.list
19
20
21def deserialize(s):
22 stack = []
23 num = ''
24 for char in s:
25 if char.isdigit() or char == '-':
26 num += char
27 elif char == '[':
28 stack.append(NestedInteger())
29 elif char == ']':
30 if num:
31 stack[-1].add(NestedInteger(int(num)))
32 num = ''
33 ni = stack.pop()
34 if stack:
35 stack[-1].add(ni)
36 else:
37 return ni
38 elif char == ',':
39 if num:
40 stack[-1].add(NestedInteger(int(num)))
41 num = ''
42 return NestedInteger(int(num)) if num else stack[0]ℹ
Complexity note: The time complexity is O(n) because we make a single pass through the string, processing each character once. The space complexity is O(n) due to the stack used for storing NestedInteger objects.
- 1Understanding how to manage nested structures is crucial.
- 2Recognizing the need for a stack to keep track of context in nested lists.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.