LeetCode Entry

1190. Reverse Substrings Between Each Pair of Parentheses

27.09.2026 medium 2026 kotlin rust

Reverse the substrings in braces

1190. Reverse Substrings Between Each Pair of Parentheses medium substack youtube

https://dmitrysamoylenko.com/leetcode/

27.09.2026.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1495

Problem TLDR

Reverse the substrings in braces

Intuition

Brute-force: a) innermost by regex b) innermost by finding first closing brace c) recursive dfs subproblem

Optimal: build the teleportation table and iterate in a separate step anim.gif

Approach

  • regex is group starting with ( brace, ending with ) brace and not having [^]* any () inside it

Complexity

  • Time complexity: \(O(n^2)\)

  • Space complexity: \(O(n)\)

Code

    fun reverseParentheses(s: String): String =  if ('(' !in s) s else
    reverseParentheses(s.replace(Regex("""\(([^()]*)\)""")) { it.groupValues[1].reversed() })
    pub fn reverse_parentheses(mut s: String) -> String {
        while let Some(r) = s.find(')') {
            let l = s[..r].rfind('(').unwrap();
            s.replace_range(l..=r, &s[l + 1..r].chars().rev().join(""))
        } s
    }

Comments