Problem
Decode an encoded string where k[encoded_string] means the substring inside the brackets is repeated k times. Encodings may nest.
Original: LeetCode 394: Decode String.
Examples
Example 1
`s = "3[a]2[bc]"``"aaabcbc"`Example 2
`s = "3[a2[c]]"``"accaccacc"`Example 3
`s = "2[abc]3[cd]ef"``"abcabccdcdcdef"`Constraints
1 <= s.length <= 30sconsists of lowercase English letters, digits, and square brackets'[]'.sis guaranteed to be a valid input.- All the integers in
sare in the range[1, 300].
Hints
Hint 1
k is a positive integer and may have more than one digit. Brackets are well formed. Letters may appear outside brackets as well as inside them.
Hint 2
Nested repeat syntax is a stack parse: the opening bracket saves the work so far, and the closing bracket expands the current segment.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Recursion on each bracketed span is the same idea as a stack, just written with the call stack.
Optimal. One scan with a stack of (previous string, repeat count) pairs, plus a buffer for the current segment and a running number.
Alternative. A recursive descent parser is clean if you already think in grammars: parse a sequence of letters and k[...] groups.
Complexity
- Time
- O(n + p)
O(n + p) time, where p is the length of the decoded result, and O(p) space.
- Space
- O(p)
Code
def decode_string(s: str) -> str:
stack: list[tuple[str, int]] = []
cur = ""
num = 0
for c in s:
if c.isdigit():
num = num * 10 + int(c)
elif c == "[":
stack.append((cur, num))
cur, num = "", 0
elif c == "]":
prev, times = stack.pop()
cur = prev + cur * times
else:
cur += c
return cur
if __name__ == "__main__":
assert decode_string("3[a]2[bc]") == "aaabcbc"
assert decode_string("3[a2[c]]") == "accaccacc"
assert decode_string("2[abc]3[cd]ef") == "abcabccdcdcdef"
print("ok")import java.util.ArrayDeque;
public class DecodeString {
static String decodeString(String s) {
var stack = new ArrayDeque<StringBuilder>();
var counts = new ArrayDeque<Integer>();
var cur = new StringBuilder();
int num = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
} else if (c == '[') {
stack.addLast(cur);
counts.addLast(num);
cur = new StringBuilder();
num = 0;
} else if (c == ']') {
var prev = stack.removeLast();
int times = counts.removeLast();
var piece = cur.toString();
for (int t = 0; t < times; t++) prev.append(piece);
cur = prev;
} else {
cur.append(c);
}
}
return cur.toString();
}
public static void main(String[] args) {
if (!decodeString("3[a]2[bc]").equals("aaabcbc")) throw new AssertionError();
if (!decodeString("3[a2[c]]").equals("accaccacc")) throw new AssertionError();
if (!decodeString("2[abc]3[cd]ef").equals("abcabccdcdcdef")) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: "3[a]2[bc]" becomes "aaabcbc", "3[a2[c]]" becomes "accaccacc", and "2[abc]3[cd]ef" becomes "abcabccdcdcdef".
- Multi-digit counts such as 10[a] must accumulate the number, not treat each digit separately.
Follow-ups
- If the decoded length could be huge, you may need to stream or bound the expansion instead of building the full string.
Interview script
"A stack remembers the text and the repeat count at each opening bracket. At a closing bracket I pop, repeat the current segment, and append it to the previous text. Digits are accumulated into the count because k can be more than one digit."
Source: LeetCode 394: Decode String
Sources (1)
- LeetCode 394: Decode Stringleetcode.com