Taro Logo

Decode String

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+27
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.6K views
Topics:
StringsStacksRecursion

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 <= 30
  • s consists of lowercase English letters, digits, and square brackets '[]'.
  • s is guaranteed to be a valid input.
  • All the integers in s are in the range [1, 300].

Solution


Clarifying Questions

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:

  1. What is the maximum possible value of $k$ (the repetition multiplier) and the maximum depth of nested brackets, and should we be concerned about integer overflow or memory limits with extremely large resulting strings?
  2. Can $k$ be a multi-digit number (e.g., `12[a]`), and should we expect any nested structures like `3[a2[c]]`?
  3. Are there cases where the input string contains no brackets at all (e.g., just plain text like `abc`), and should it be returned as-is?
  4. Should we assume the input string is always strictly valid according to the rules, or do we need to handle or validate malformed inputs?
  5. What character set does the encoded string contain? Are we only dealing with lowercase English letters and digits, or could there be special characters, spaces, or uppercase letters?

Brute Force Solution

Approach

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:

  1. Read through the encoded message from beginning to end to find the first set of brackets that contains a number and some letters.
  2. Pause when you find the deepest set of brackets, because those are nested inside everything else and must be solved first.
  3. Look at the number written right outside those brackets to see how many times the inner letters need to be repeated.
  4. Erase the brackets, the number, and write out those letters the exact specified number of times right in that spot.
  5. Look at your newly updated message and repeat this entire process from the very beginning.
  6. Keep doing this search and rewrite process over and over again every time you spot remaining brackets.
  7. Stop only when you scan the entire message from start to finish and find zero brackets remaining, leaving you with the fully decoded message.

Code Implementation

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_message

Big(O) Analysis

Time Complexity
O(n * k) – The process repeatedly scans the message of length n and performs string reconstruction steps based on the repeat counts inside the brackets. In the worst-case scenario with nested or repeated patterns, the cost is driven by repeatedly rewriting substrings up to a total decoded length proportional to n times the maximum repetition factor k. Summing these string manipulation costs across each decoding pass yields approximately n * k operations. Simplifying this complexity gives a final runtime of O(n * k).
Space Complexity
O(N) – To handle the nested brackets and repetition counts described in the puzzle, the algorithm utilizes explicit data structures such as a character stack and a number stack, or alternatively, a recursion call stack. In the worst-case scenario where the encoded message contains deeply nested patterns, these stacks will store intermediate characters and multipliers proportional to the length of the input string N. Therefore, the auxiliary memory consumed by these tracking mechanisms scales directly with N, leading to an overall space complexity of Big O of N.

Optimal Solution

Approach

To 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:

  1. Read through the encoded message character by character from the beginning.
  2. Whenever you encounter a regular letter or a number, keep track of it so you know what is being built and how many times it needs to repeat.
  3. When you hit an opening marker for a repeated section, pause what you are currently working on and safely store your current progress and repetition count in your mental storage.
  4. Reset your workspace to start building the new, inner section inside the parentheses.
  5. When you reach a closing marker, it means you have finished the inner section.
  6. Take the completed inner piece, repeat it as many times as your stored count dictates, and attach it to the previous work you pulled back out from your mental storage.
  7. Continue this process until you reach the very end of the message, resulting in the fully decoded text.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(maxK * n) – As we iterate through the input string of length n character by character, we build and repeat substrings based on the decoded multipliers. In the worst-case scenario with nested repetitions, a character may be processed and appended to our working string multiple times proportional to the maximum repetition value k. Summing these operations across the length of the string results in approximately n times maxK total operations. This simplifies to a linear-time complexity with respect to the final output size, expressed as O(maxK * n).
Space Complexity
O(N) – The auxiliary space is driven by the stacks used for mental storage to hold previous string builders and repetition counts when nested parentheses are encountered. In the worst-case scenario of deeply nested or completely sequential encoded segments, these stacks will grow proportionally to the input length N. Additionally, the final decoded string and intermediate substrings stored in the stack consume memory that scales with N. Therefore, the total extra memory required by the algorithm simplifies in Big O notation to O(N).

Edge Cases

String with no brackets containing only plain letters
How to Handle:
The stack or recursive approach simply passes through characters without modification and returns the original string.
Nested brackets such as 3[a2[c]]
How to Handle:
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]
How to Handle:
The parser must accumulate contiguous digits into a full integer before encountering the opening bracket.
Consecutive independent encoded segments like 3[a]2[bc]
How to Handle:
The algorithm processes each segment sequentially, appending results to the current string builder without state bleeding.
Deeply nested brackets exceeding normal recursion depth limits
How to Handle:
An iterative stack-based implementation avoids stack overflow errors associated with deep recursion.
Maximum-sized output string causing memory reallocation overhead
How to Handle:
Using efficient string builders or accumulating character arrays prevents quadratic time complexity from repeated string concatenation.
Single character input inside brackets like 1[a]
How to Handle:
The multiplication logic correctly repeats the single character the specified number of times and merges it with the running result.
0/75 completed