VOOZH about

URL: https://www.geeksforgeeks.org/dsa/repeat-substrings-of-the-given-string-required-number-of-times/

⇱ Repeat substrings of the given String required number of times - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Repeat substrings of the given String required number of times

Last Updated : 12 Jul, 2025

Given string str, the task is to repeat every substring of the string X number of times where X is the number composed of the consecutive digits present just after the substring in the original string. For example, if str = "g1e2ks1" then the resultant string will be "geeks". Examples:

Input: str = "2a10bd3"
Output: aaaaaaaaaabdbdbd
Explanation: First digit "2" is unnecessary as there is no valid substring before it. "a" will be repeated 10 times and then "bd" will be repeated thrice.

Input: str = "g1ee1ks1for1g1e2ks1"
Output: geeksforgeeks

Approach: Find the first valid substring i.e. the substring which doesn't contain any digit then parse the integer present just after the found substring using parseInt() and then repeat the found substring the required number of times. Repeat these steps for all valid substrings and then print the resultant string. Below is the implementation of the above approach: 

Output:
geeksforgeeks

Time Complexity: O(n2) where n is the length of the string.
Auxiliary Space: O(n)

Comment
Article Tags: