TikTok VO Interview Coding Question: Decode String

20 Views
No Comments

Decode String

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is repeated exactly k times. k is guaranteed to be a positive integer.

You may assume that the input string is always valid; there are no extra spaces, and the brackets are well-formed.

Also, you may assume that the original data does not contain any digits, and that digits only represent repeat counts k, so inputs such as 3a or 2[4] will not appear.

Examples:

1. Input: s = "3[a]2[bc]"
   Output: "aaabcbc"

2. Input: s = "3[a2[c]]"
   Output: "accaccacc"

3. Input: s = "2[abc]3[cd]ef"
   Output: "abcabccdcdcdef"

4. Input: s = "abc3[cd]xyz"
   Output: "abccdcdcdxyz"

This problem asks you to decode a nested repetition format of the form <code>k[encoded_string]</code>. A stack-based approach is the standard solution: store the previous string and repeat count when you see an opening bracket, accumulate digits for multi-digit multipliers, and rebuild the current segment when you meet a closing bracket. It handles examples like <code>3[a2[c]]</code> naturally and runs in linear time over the input length.

END
 0