Browse curriculum

FAANGPrep Sprint

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

"3[a2[c]]"

READ

encoded

i

3

0

[

1

a

2

2

3

[

4

c

5

]

6

]

7

stack

empty

chunk

—

k

—

Result

—

 

Read '3' at 0

Next

'3' is not ']': push it

Encoded

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