Program to expand string represented as n(t) format in Python

String expansion in the n(t) format is a common programming problem where we need to decode compressed strings. The format n(t) means concatenate string t exactly n times, and t can be either a regular string or another encoded string recursively.

So, if the input is like s = "3(pi)2(3(am))0(f)1(u)", then the output will be "pipipiamamamamamamu".

Algorithm Steps

To solve this problem, we will follow these steps ?

  • Initialize index i := 0

  • Define a recursive function parse() that processes the string

  • Create an empty result list

  • While i < string length and current character is not ')', do:

    • If current character is a digit:

      • Extract the complete number

      • Skip the opening parenthesis

      • Recursively parse the content inside parentheses

      • Skip the closing parenthesis

      • Repeat the parsed content n times

    • Otherwise, add the character directly to result

  • Return the joined result string

Example

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, s):
        i = 0
        
        def parse():
            nonlocal i
            ans = []
            
            while i < len(s) and s[i] != ")":
                if s[i].isdigit():
                    # Extract the number
                    d = 0
                    while i < len(s) and s[i].isdigit():
                        d = 10 * d + int(s[i])
                        i += 1
                    
                    # Skip opening parenthesis
                    i += 1
                    
                    # Parse content inside parentheses
                    segment = parse()
                    
                    # Skip closing parenthesis
                    i += 1
                    
                    # Add segment d times
                    ans.extend([segment] * d)
                else:
                    # Regular character
                    ans.append(s[i])
                    i += 1
            
            return "".join(ans)
        
        return parse()

# Test the solution
ob = Solution()
s = "3(pi)2(3(am))0(f)1(u)"
print(ob.solve(s))

The output of the above code is ?

pipipiamamamamamamu

How It Works

The algorithm uses a recursive approach with a nested parse function. Here's the breakdown:

  • Digit detection: When we encounter a digit, we extract the complete number

  • Parentheses handling: Skip opening parenthesis, recursively parse content, skip closing parenthesis

  • String repetition: Multiply the parsed segment by the extracted number

  • Regular characters: Add them directly to the result

Test with Different Examples

ob = Solution()

# Test case 1: Simple repetition
print(ob.solve("2(abc)"))

# Test case 2: Nested structure
print(ob.solve("2(b3(a))"))

# Test case 3: Zero repetitions
print(ob.solve("3(a)0(b)2(c)"))
abcabc
baaabaa
aaacccc

Conclusion

This recursive parsing approach efficiently handles nested string expansion by processing digits, parentheses, and regular characters systematically. The algorithm correctly expands strings in n(t) format, supporting nested structures and zero repetitions.

Updated on: 2026-03-25T13:52:44+05:30

434 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements