Decode string

Python data engineering interview problem. Difficulty: intermediate. Pattern: Stacks. About 16 minutes. Part of the Pro drill bank.

Decode strings with repeated bracketed segments, handling nested repetitions and multi-digit multipliers. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

Implement decode_string(s: str) -> str to decode an encoded pattern. The encoding format is k[encoded_string], where encoded_string inside the square brackets is repeated exactly k times. k is a positive integer (which may be multi-digit). Brackets can be nested arbitrarily, such as 3[a2[c]]. Characters outside of brackets remain as they are.

Requirements

  • Inner brackets must be fully decoded before outer repetition is applied.
  • Multi-digit numbers must be parsed as a whole.

Constraints

  • 1 <= len(s) <= 1,000
  • s consists of lowercase English letters, digits, and square brackets '[' and ']'.
  • All integers k are in the range [1, 300].

Examples

Input: decode_string('3[a]2[bc]') Output: 'aaabcbc' The first section repeats 'a' 3 times, followed by 'bc' repeated twice.

Topics: lakebench, python, bracket-matching, nested-brackets.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Decode string

Interview-style drill: Decode strings with repeated bracketed segments, handling nested repetitions and multi-digit multipliers.

Implement `decode_string(s: str) -> str` to decode an encoded pattern. The encoding format is `k[encoded_string]`, where `encoded_string` inside the square brackets is repeated exactly `k` times. - `k` is a positive integer (which may be multi-digit). - Brackets can be nested arbitrarily, such as `3[a2[c]]`. - Characters outside of brackets remain as they are.