Tutorialspoint
Problem
Solution
Submissions

Decode String

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid.

Example 1
  • Input: s = "3[a]2[bc]"
  • Output: "aaabcbc"
  • Explanation:
    • Process "3[a]" - repeat 'a' three times to get "aaa".
    • Process "2[bc]" - repeat "bc" two times to get "bcbc".
    • Concatenate results: "aaa" + "bcbc" = "aaabcbc".
    • Final decoded string is "aaabcbc".
Example 2
  • Input: s = "2[a3[c]b]"
  • Output: "accbaccb"
  • Explanation:
    • Start with innermost brackets "3[c]" - repeat 'c' three times to get "ccc".
    • Replace in original: "2[acccb]". Process "2[acccb]" - repeat "acccb" two times.
    • Final result: "acccb" + "acccb" = "accbaccb".
    • Note: 'ccc' becomes 'cc' in each repetition due to the pattern "a3[c]b".
Constraints
  • 1 ≤ s.length ≤ 30
  • s consists of lowercase English letters, digits, and square brackets '[]'
  • s is guaranteed to be a valid input
  • All the integers in s are in the range [1, 300]
  • Time Complexity: O(n) where n is the length of the decoded string
  • Space Complexity: O(n) for the stack
StringsStackIBMAirbnb
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a stack to handle nested brackets and keep track of strings and their repetition counts
  • Process the string character by character, building numbers and strings
  • When encountering '[', push current string and number to stack
  • When encountering ']', pop from stack and repeat the current string
  • Handle nested structures by maintaining separate stacks for strings and numbers

Steps to solve by this approach:

 Step 1: Initialize a stack to store previous strings and numbers, and variables for current number and string.
 Step 2: Iterate through each character in the input string.
 Step 3: If character is a digit, build the current number by multiplying by 10 and adding the digit.
 Step 4: If character is '[', push current string and number to stack, then reset them.
 Step 5: If character is ']', pop previous string and number from stack, repeat current string and concatenate.
 Step 6: If character is a letter, append it to the current string.
 Step 7: Return the final decoded string after processing all characters.

Submitted Code :