Decode String
Problem
You are given an encoded string. The encoding rule is k[inner], meaning the string inner is repeated exactly k times, where k is a positive integer and inner may itself contain further encoded segments. Plain letters outside any brackets are copied as-is. Return the fully decoded string.
- The encoded string has between 1 and 100 characters.
scontains only lowercase letters, digits, and square brackets.- Digits appear only as repeat counts (never as literal text), and every count is between 1 and 200.
- The input is always well-formed.
Examples
s = "2[xy]4[q]"→"xyxyqqqq". Two independent groups, one after the other.s = "2[p3[e]]"→"peeepeee". The inner3[e]expands toeeefirst, thenp+eeeis repeated twice.s = "4[hi]2[jk]lm"→"hihihihijkjklm". Trailing plain letters are appended unchanged.
Hints
- A
]closes the most recently opened[. What must you remember at each[so that you can finish the group when its]arrives? - You need the repeat count for this group and the text accumulated before the group started.
- Push
(prefix_so_far, count)on[; on]pop and set the current string toprefix + current * count.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.