InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Stack

Decode String

medium Original ↗ 00:00

Problem

You get an encoded string that uses the rule k[segment]: the segment inside the square brackets is repeated exactly k times (k is a positive integer, always present before a [). Encodings can nest — a bracketed segment may itself contain more k[...] blocks. Plain lowercase letters outside any brackets are copied through unchanged, and digits appear only as repeat counts.

Return the fully decoded string. The input is guaranteed well-formed.

Examples

  • "3[a]2[bc]""aaabcbc"a three times, then bc twice.
  • "3[a2[c]]""accaccacc" — inner 2[c] becomes cc, so the outer block repeats acc three times.
  • "2[abc]3[cd]ef""abcabccdcdcdef" — two blocks, then a plain tail ef.

Constraints

  • 1 <= s.length <= 30
  • 1 <= k <= 300; the decoded output is guaranteed to fit (at most ~10^5 characters)
  • s contains only lowercase letters, digits, and square brackets, and is always valid

The input is tiny, but nesting means the output can be large — the expected solution is a single left-to-right pass, linear in the output size.

Think about it first

Hint 1 In `"3[a2[c]]"`, when you reach the first `]`, which `[` does it close? The most recently opened one. That is last-in-first-out order, which a stack gives you.
Hint 2 Build the current segment as you scan. When you hit `[`, you must *suspend* what you've built (and the repeat count you just read) and start fresh; when you hit `]`, you resume the suspended work. Suspend/resume in last-in-first-out order is a stack of `(previous_string, count)` frames.
Hint 3 One pass: accumulate multi-digit `num` on digits; on `[` push `(current, num)` and reset both; on `]` pop `(prev, k)` and set `current = prev + current * k`; on a letter, append it. `current` at the end is the answer.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug