Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4].
The test cases are generated so that the length of the output will never exceed 105.
Example 1:
Input: s = "3[a]2[bc]" Output: "aaabcbc"
Example 2:
Input: s = "3[a2[c]]" Output: "accaccacc"
Example 3:
Input: s = "2[abc]3[cd]ef" Output: "abcabccdcdcdef"
Constraints:
1 <= s.length <= 30s consists of lowercase English letters, digits, and square brackets '[]'.s is guaranteed to be a valid input.s are in the range [1, 300].When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are holding a secret message written with repeated chunks, like a compressed puzzle. The brute force approach involves repeatedly searching for the innermost secret pattern and manually writing it out over and over again until no patterns are left.
Here's how the algorithm would work step-by-step:
def decode_string(encoded_message):
while '[' in encoded_message:
# We scan backwards to find the innermost opening bracket so we resolve nesting correctly
opening_index = encoded_message.rfind('[')
closing_index = opening_index
while encoded_message[closing_index] != ']':
closing_index += 1
number_index = opening_index - 1
while number_index >= 0 and encoded_message[number_index].isdigit():
number_index -= 1
repeat_count = int(encoded_message[number_index + 1:opening_index])
inner_pattern = encoded_message[opening_index + 1:closing_index]
# Expanding the segment in place is necessary to replace the encoded chunk with its repetition
expanded_chunk = inner_pattern * repeat_count
encoded_message = encoded_message[:number_index + 1] + expanded_chunk + encoded_message[closing_index + 1:]
# Returning the fully transformed string ensures we only finish once all nested brackets are gone
return encoded_messageTo decode a message where parts are repeated, the optimal approach uses a mental storage system to remember what came before when parentheses appear. By processing the message piece by piece, we can properly expand the nested repetitions from the inside out.
Here's how the algorithm would work step-by-step:
def decode_string(encoded_message):
stack_of_previous_states = []
current_string_builder = ""
current_repeat_counter = 0
# We iterate through the encoded message character by character to handle nesting.
for current_character in encoded_message:
if current_character.isdigit():
current_repeat_counter = (current_repeat_counter * 10) + int(current_character)
elif current_character == '[':
# We pause current work and store state so we can build the inner section.
stack_of_previous_states.append((current_string_builder, current_repeat_counter))
current_string_builder = ""
current_repeat_counter = 0
elif current_character == ']':
# We finish the inner section and combine it with our previous progress.
previous_string_builder, repetition_count = stack_of_previous_states.pop()
current_string_builder = previous_string_builder + (current_string_builder * repetition_count)
else:
current_string_builder += current_character
return current_string_builder| Case | How to Handle |
|---|---|
| String with no brackets containing only plain letters | The stack or recursive approach simply passes through characters without modification and returns the original string. |
| Nested brackets such as 3[a2[c]] | Using a stack allows us to push current strings and counts when encountering an opening bracket and pop to combine them on a closing bracket. |
| Multi-digit repeat counts such as 100[a] | The parser must accumulate contiguous digits into a full integer before encountering the opening bracket. |
| Consecutive independent encoded segments like 3[a]2[bc] | The algorithm processes each segment sequentially, appending results to the current string builder without state bleeding. |
| Deeply nested brackets exceeding normal recursion depth limits | An iterative stack-based implementation avoids stack overflow errors associated with deep recursion. |
| Maximum-sized output string causing memory reallocation overhead | Using efficient string builders or accumulating character arrays prevents quadratic time complexity from repeated string concatenation. |
| Single character input inside brackets like 1[a] | The multiplication logic correctly repeats the single character the specified number of times and merges it with the running result. |