Browse Curriculum
FAANGPrep Sprint
Medium

Decode String

Decode an encoded string with nested repetition rules.

Problem Understanding

You are given an encoded string where k[encoded_string] means the encoded_string inside the brackets is repeated exactly k times. You may assume the input string is always valid.

Example:

  • Input: 3[a]2[bc] -> Output: aaabcbc
  • Input: 3[a2[c]] -> Output: accaccacc (Nested!)

Algorithm Strategy

We use a Stack to handle the nested nature of the problem.

  1. Initialize an empty stack.
  2. Iterate through the string character by character.
  3. If the char is NOT ], push it to the stack.
  4. If the char IS ], we must start decoding:
    • Pop characters until we find [. This is the string_to_repeat.
    • Pop the [.
    • Pop numbers to form k (the repetition count).
    • Repeat string_to_repeat k times and Push it back to the stack.
  5. Finally, join the stack to get the result.

Interactive Visualization

Step 1 / 1
Empty Stack
Top Index: -1

Initializing...

1x

Visualize how the stack builds nested strings from the inside out.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.