Decompress encoded string with nested repeats
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates string parsing and manipulation skills, particularly handling nested repetition encodings and reasoning about output growth, and belongs to the Coding & Algorithms domain.
Constraints
- 0 <= len(s) <= 100000
- Each repetition count `n` is an integer from 2 to 99
- Every `{n}` appears immediately after a `)`
- Parentheses and braces are properly matched
- The length of the decompressed output will not exceed 10^6 characters
Examples
Input: ("a(abc){3}",)
Expected Output: "aabcabcabc"
Explanation: The group `(abc)` expands to `abcabcabc`, and the leading `a` stays in front.
Input: ("a(b(c){2}){3}d",)
Expected Output: "abccbccbccd"
Explanation: `(c){2}` becomes `cc`, so `(bcc){3}` becomes `bccbccbcc`, then add the outer `a` and `d`.
Input: ("",)
Expected Output: ""
Explanation: An empty input decompresses to an empty string.
Input: ("plain",)
Expected Output: "plain"
Explanation: There are no groups, so the string stays unchanged.
Input: ("(ab){12}",)
Expected Output: "abababababababababababab"
Explanation: The group `ab` is repeated 12 times.
Input: ("(a){2}(b){3}",)
Expected Output: "aabbb"
Explanation: The first group becomes `aa`, and the second becomes `bbb`.
Hints
- Use a stack to remember the already-built prefix whenever you enter a new parenthesized group.
- When you reach `)`, parse the number inside the following braces, expand the current group, and append it back to the previous level.