KatInterview

385. Mini Parser

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Iterative Approach using a Stack

The problem requires us to parse a string representation of a nested data structure. The structure is recursive: a list can contain integers or other lists. This type of nested structure is a classic use case for a stack, which helps manage the levels of nesting.

Solution

Mini Parser in Python

class Solution:
    def deserialize(self, s: str) -> NestedInteger:
        # If the string doesn't start with '[', it's a single integer.
        if not s.startswith('['):
            return NestedInteger(int(s))
            
        stack = []
        start = 0 # Marks the starting index of a number
        
        for i, char in enumerate(s):
            if char == '[':
                # Start of a new nested list
                stack.append(NestedInteger())
                start = i + 1
            elif char == ',' or char == ']':
                # A number ends at i-1
                if i > start:
                    num = int(s[start:i])
                    stack[-1].add(NestedInteger(num))
                # Reset start for the next potential number
                start = i + 1
                
                if char == ']' and len(stack) > 1:
                    # A list is complete. If it's a nested list, add it to its parent.
                    ni = stack.pop()
                    stack[-1].add(ni)
        
        # The last remaining item on the stack is the final result.
        return stack[0]

Mini Parser in Java

class Solution {
    public NestedInteger deserialize(String s) {
        // If the string doesn't start with '[', it's a single integer.
        if (!s.startsWith("[")) {
            return new NestedInteger(Integer.parseInt(s));
        }
        
        Stack<NestedInteger> stack = new Stack<>();
        int start = 0; // Marks the starting index of a number

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c == '[') {
                // Start of a new nested list
                stack.push(new NestedInteger());
                start = i + 1;
            } else if (c == ',' || c == ']') {
                // A number ends at i-1
                if (i > start) {
                    String numStr = s.substring(start, i);
                    int val = Integer.parseInt(numStr);
                    stack.peek().add(new NestedInteger(val));
                }
                // Reset start for the next potential number
                start = i + 1;

                if (c == ']') {
                    // A list is complete. If it's a nested list, add it to its parent.
                    if (stack.size() > 1) {
                        NestedInteger ni = stack.pop();
                        stack.peek().add(ni);
                    }
                }
            }
        }
        // The last remaining item on the stack is the final result.
        return stack.pop();
    }
}

Mini Parser in C++

class Solution {
public:
    NestedInteger deserialize(string s) {
        // If the string doesn't start with '[', it's a single integer.
        if (s.empty()) {
            return NestedInteger();
        }
        if (s[0] != '[') {
            return NestedInteger(stoi(s));
        }

        stack<NestedInteger> st;
        int start = 0; // Marks the starting index of a number

        for (int i = 0; i < s.length(); ++i) {
            char c = s[i];

            if (c == '[') {
                // Start of a new nested list
                st.push(NestedInteger());
                start = i + 1;
            } else if (c == ',' || c == ']') {
                // A number ends at i-1
                if (i > start) {
                    string numStr = s.substr(start, i - start);
                    int val = stoi(numStr);
                    st.top().add(NestedInteger(val));
                }
                // Reset start for the next potential number
                start = i + 1;

                if (c == ']') {
                    // A list is complete. If it's a nested list, add it to its parent.
                    if (st.size() > 1) {
                        NestedInteger ni = st.top();
                        st.pop();
                        st.top().add(ni);
                    }
                }
            }
        }
        // The last remaining item on the stack is the final result.
        return st.top();
    }
};

Mini Parser in TypeScript

function deserialize(s: string): NestedInteger {
    // If the string doesn't start with '[', it's a single integer.
    if (!s.startsWith('[')) {
        return new NestedInteger(parseInt(s));
    }
    
    const stack: NestedInteger[] = [];
    let start = 0; // Marks the starting index of a number
    
    for (let i = 0; i < s.length; i++) {
        const char = s[i];
        
        if (char === '[') {
            // Start of a new nested list
            stack.push(new NestedInteger());
            start = i + 1;
        } else if (char === ',' || char === ']') {
            // A number ends at i-1
            if (i > start) {
                const numStr = s.substring(start, i);
                const val = parseInt(numStr);
                stack[stack.length - 1].add(new NestedInteger(val));
            }
            // Reset start for the next potential number
            start = i + 1;
            
            if (char === ']' && stack.length > 1) {
                // A list is complete. If it's a nested list, add it to its parent.
                const ni = stack.pop()!;
                stack[stack.length - 1].add(ni);
            }
        }
    }
    
    // The last remaining item on the stack is the final result.
    return stack.pop()!;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.