Coding · must-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Decode String

mediumstackrecursionparsing

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.
  • s contains 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 inner 3[e] expands to eee first, then p + eee is repeated twice.
  • s = "4[hi]2[jk]lm" → "hihihihijkjklm". Trailing plain letters are appended unchanged.

Hints

  1. A ] closes the most recently opened [. What must you remember at each [ so that you can finish the group when its ] arrives?
  2. You need the repeat count for this group and the text accumulated before the group started.
  3. Push (prefix_so_far, count) on [; on ] pop and set the current string to prefix + current * count.

Last reviewed 8 September 2026