Skip to main content

1190. Reverse Substrings Between Each Pair of Parentheses

Problem Description​

You are given a string s that consists of lower case English letters and brackets.

Reverse the strings in each pair of matching parentheses, starting from the innermost one.

Your result should not contain any brackets.

Examples​

Example 1:

Input: s = "(u(love)i)"
Output: "iloveu"
Explanation: The substring "love" is reversed first, then the whole string is reversed.

Constraints​

  • 1 <= s.length <= 2000
  • s only contains lower case English characters and parentheses.
  • It is guaranteed that all parentheses are balanced.

Solution for 1190. Reverse Substrings Between Each Pair of Parentheses​

Implementation​

Live Editor
function Solution(arr) {
    var reverseParentheses = function(s) {
    let st = [];
    let arr = s.split('');
    
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === '(') {
            st.push(i);
        } else if (arr[i] === ')') {
            let top = st.pop();
            reverse(arr, top + 1, i - 1);
        }
    }
    
    let ans = '';
    for (let c of arr) {
        if (/[a-z]/.test(c)) {
            ans += c;
        }
    }
    return ans;
};

function reverse(arr, left, right) {
    while (left < right) {
        let temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        left++;
        right--;
    }
}

  const input = "(u(love)i)"
  const output = reverseParentheses(input)
  return (
    <div>
      <p>
        <b>Input: </b>
        {JSON.stringify(input)}
      </p>
      <p>
        <b>Output:</b> {output.toString()}
      </p>
    </div>
  );
}
Result
Loading...

Complexity Analysis​

  • Time Complexity: O(n2)O(n^2)
  • Space Complexity: O(n) O(n)

Code in Different Languages​

Written by @hiteshgahanolia
class Solution:
def reverseParentheses(self, s: str) -> str:
st = []
s = list(s)

for i in range(len(s)):
if s[i] == '(':
st.append(i)
elif s[i] == ')':
top = st.pop()
s[top + 1:i] = s[top + 1:i][::-1]

return ''.join(c for c in s if c.isalpha())

References​