Decode an encoded string
Company: Instacart
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates string parsing and manipulation skills, particularly handling nested repetition encodings and managing state when expanding bracketed substrings.
Constraints
- `0 <= len(s) <= 10^5`
- `s` contains only letters, digits, `[` and `]`
- Every bracketed pattern is valid and every repeat count is a positive integer
- The length of the decoded string will not exceed `10^6`
Examples
Input: "3[a]2[bc]"
Expected Output: "aaabcbc"
Explanation: `3[a]` becomes `aaa` and `2[bc]` becomes `bcbc`, so the final result is `aaabcbc`.
Input: "3[a2[c]]"
Expected Output: "accaccacc"
Explanation: Inside the outer pattern, `a2[c]` becomes `acc`. Repeating that 3 times gives `accaccacc`.
Hints
- Use a stack to remember the string built so far and the repeat count when you encounter `[`. When you see `]`, you can expand the current segment.
- Be careful with counts like `10[a]` or `23[bc]` — the number may have more than one digit.