Skip to content

Reverse In Parentheses

Write a function that reverses characters in (possibly nested) parentheses in the input string.

Input strings will always be well-formed with matching ()s.

Example

  • For inputString = "(bar)", the output should be

    reverse_in_parentheses(inputString) = "rab"
  • For inputString = "foo(bar)baz", the output should be

    reverse_in_parentheses(inputString) = "foorabbaz"
  • For inputString = "foo(bar)baz(blim)", the output should be

    reverse_in_parentheses(inputString) = "foorabbazmilb"
  • For inputString = "foo(bar(baz))blim", the output should be

    reverse_in_parentheses(inputString) = "foobazrabblim"

    Because "foo(bar(baz))blim" becomes "foo(barzab)blim" and then "foobazrabblim".

Solution

py
import re


def reverse_in_parentheses(inputString):
    m = re.search(r"\(([^()]*)\)", inputString)
    if m is None:
        return inputString
    return reverse_in_parentheses(inputString[: m.start()] + m.group(1)[::-1] + inputString[m.end():])


print(reverse_in_parentheses("(bar)"))
js
function reverseInParentheses(inputString) {
  const regex = /\(([^()]*)\)/;
  let result = inputString;
  let match = result.match(regex);

  while (match) {
    const reversed = match[1].split('').reverse().join('');
    result = result.replace(regex, reversed);
    match = result.match(regex);
  }

  return result;
}

console.log(reverseInParentheses('foo(bar(baz))blim'));

my thoughts are neither my employer's nor my wife's