Problem · String

Decode an Encoded String

Learn this problem
MediumAmazon logoAmazonFULLTIMEONSITE INTERVIEW
See Amazon hiring insights

Problem statement

An encoded string uses positive repeat counts followed by bracketed segments. Decode it using these rules:

  • k[segment] means the decoded segment is repeated exactly k times.
  • Segments may be nested.
  • Letters outside brackets appear once and remain in order.

Return the fully decoded string.

Function

decodeString(s: String) → String

Examples

Example 1

s = "3[a2[c]]"return = "accaccacc"

The inner block becomes acc, then the outer count repeats it three times.

Example 2

s = "2[ab]3[c]"return = "ababccc"

The two adjacent encoded blocks decode independently and are concatenated.

Constraints

  • 1 <= s.length <= 10^4
  • s is a well-formed encoding made of lowercase English letters, digits, and brackets.
  • Every repeat count is between 1 and 300.
  • The decoded string has at most 10^5 characters.

More Amazon problems

drafts saved locally
public String decodeString(String s) {
    // Write your solution here.
}
s"3[a2[c]]"
expected"accaccacc"
checking account