Daily Coding Challenge - Reverse Parenthesis

Tell us what’s happening:

Is using regular expression the best approach to tackle this challenge? I’ve written one solution with re module, and wonder whether it can be done with built-in Python functions, but it seems to be quite complex to do so.

Your code so far

import re

def decode(s):
    p = r'\([^()]*\)' # search pattern: '(', non-parenthesis characters and ')'
    matched = re.search(p, s)
    while matched:
        repl = matched.group(0)[1:-1][::-1] # stripped the parenthesis and reverse the characters
        s = re.sub(p, repl, s, 1) #replace the matched substring
        matched = re.search(p, s)
    return s

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36

Challenge Information:

Daily Coding Challenge - Reverse Parenthesis

https://www.freecodecamp.org/learn/daily-coding-challenge/2025-08-26

Well, technically speaking the re module is built-in :face_with_tongue: , so that requirement is already met.

1 Like

I solved this using a stack and queue implemented with linked lists. Not nearly as concise as using regular expressions, though you could just use arrays instead of linked lists if you wanted to get the line count down.

Mod Edit: SOLUTION REMOVED

1 Like

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge. How to Help Someone with Their Code Using the Socratic Method

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

I’ve figured out how to do it with basic functions. Basically it’s using a for loop to find the index of the last open parenthesis, then the index of the next close parenthesis. Then use these indexes to select the characters in between and reverse them, and use string concatenation to attach the substrings before the open parenthesis and after the close parenthesis. The whole process is repeated using a while loop until there is no parenthesis.

1 Like