LeetCode 1190: Reverse Substrings Between Each Pair of Parentheses Solution

Master LeetCode problem 1190 (Reverse Substrings Between Each Pair of Parentheses), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1190. Reverse Substrings Between Each Pair of Parentheses

Problem Explanation

Explanation

To solve this problem, we can use a stack to keep track of the indices of the opening parentheses. We iterate through the string and whenever we encounter an opening parenthesis, we push its index onto the stack. When we encounter a closing parenthesis, we pop the index of the corresponding opening parenthesis and reverse the substring between these two indices. We continue this process until we have processed the entire string.

Time Complexity

The time complexity of this solution is O(n), where n is the length of the input string.

Space Complexity

The space complexity of this solution is O(n) due to the stack used to store the indices of opening parentheses.

Solution Code

class Solution {
    public String reverseParentheses(String s) {
        Stack<Integer> stack = new Stack<>();
        int n = s.length();
        char[] arr = s.toCharArray();

        for (int i = 0; i < n; i++) {
            if (arr[i] == '(') {
                stack.push(i);
            } else if (arr[i] == ')') {
                int start = stack.pop();
                reverseSubstring(arr, start + 1, i - 1);
            }
        }

        StringBuilder sb = new StringBuilder();
        for (char c : arr) {
            if (c != '(' && c != ')') {
                sb.append(c);
            }
        }

        return sb.toString();
    }

    private void reverseSubstring(char[] arr, int left, int right) {
        while (left < right) {
            char temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1190 (Reverse Substrings Between Each Pair of Parentheses)?

This page provides optimized solutions for LeetCode problem 1190 (Reverse Substrings Between Each Pair of Parentheses) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1190 (Reverse Substrings Between Each Pair of Parentheses)?

The time complexity for LeetCode 1190 (Reverse Substrings Between Each Pair of Parentheses) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1190 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1190 in Java, C++, or Python.

Back to LeetCode Solutions