VOOZH about

URL: https://www.geeksforgeeks.org/dsa/expand-the-string-according-to-the-given-conditions/

⇱ Expand the string according to the given conditions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Expand the string according to the given conditions

Last Updated : 12 Jul, 2025

Given string str of the type "3(ab)4(cd)", the task is to expand it to "abababcdcdcdcd" where integers are from the range [1, 9].
This problem was asked in ThoughtWorks interview held in October 2018.


Examples:

Input: str = "3(ab)4(cd)" 
Output: abababcdcdcdcd
Input: str = "2(kl)3(ap)" 
Output: klklapapap 

Approach: We traverse through the string and wait for a numeric value, num to turn up at position i. As soon as it arrives, we check i + 1 for a '('. If it's present, then the program enters into a loop to extract whatever is within '(' and ')' and concatenate it to an empty string, temp. Later, another loop prints the generated string num number of times. Repeat these steps until the string finishes.


Below is the implementation of the approach: 


Output
abababcdcdcdcd

Time Complexity: O(N*N)
Auxiliary Space: O(1)

Approach using Stack:

To enhance the efficiency of solutions for decoding strings with nested encodings across different programming languages, we can adopt a unified and optimal approach utilizing data structures and language-specific string manipulation capabilities. This optimized strategy can be applied broadly, irrespective of the programming language, by following these key principles:

Below is the implementation of above approach:

  • Use a stack to manage nested encodings. Push tuples or pairs onto the stack.
  • As the input is parsed, construct numeric multipliers when digits are encountered.
  • When a start marker like ( is encountered, push the current state onto the stack and reset your working string and multiplier. ), pop the stack to get the context (the string before this nested sequence and the multiplier).
  • Repeat the current string segment as specified by the multiplier and concatenate it with the string retrieved from the stack.
  • Once the entire string has been parsed, the current working string (stored in a variable like current_string) will hold the fully decoded string.

Below is the implementation of above approach:


Output
abababcdcdcdcd

Time Complexity: O(n), where n is the length of the input string. The complexity arises from iterating through each character in the string and possibly multiplying substrings. The actual time complexity in practice is very close to linear because each character is effectively processed a fixed number of times due to the stack operations.

Auxilary Space: O(n), as in the worst case, the stack and the current_string combined may hold nearly an entire copy of the input string, especially in cases where the string is deeply nested or contains many repeated segments.


Comment
Article Tags:
Article Tags: