Skip to content

1541. Minimum Insertions to Balance a Parentheses String

Description

Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:

  • Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.
  • Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.

In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis.

  • For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not balanced.

You can insert the characters '(' and ')' at any position of the string to balance it if needed.

Return the minimum number of insertions needed to make s balanced.

 

Example 1:

Input: s = "(()))"
Output: 1
Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(())))" which is balanced.

Example 2:

Input: s = "())"
Output: 0
Explanation: The string is already balanced.

Example 3:

Input: s = "))())("
Output: 3
Explanation: Add '(' to match the first '))', Add '))' to match the last '('.

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of '(' and ')' only.

Solutions

Solution 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
    def minInsertions(self, s: str) -> int:
        ans = x = 0
        i, n = 0, len(s)
        while i < n:
            if s[i] == '(':
                # εΎ…εŒΉι…ηš„ε·¦ζ‹¬ε·εŠ  1
                x += 1
            else:
                if i < n - 1 and s[i + 1] == ')':
                    # ζœ‰θΏžη»­δΈ€δΈͺε³ζ‹¬ε·οΌŒi εΎ€εŽη§»εŠ¨
                    i += 1
                else:
                    # εͺζœ‰δΈ€δΈͺε³ζ‹¬ε·οΌŒζ’ε…₯δΈ€δΈͺ
                    ans += 1
                if x == 0:
                    # ζ— εΎ…εŒΉι…ηš„ε·¦ζ‹¬ε·οΌŒζ’ε…₯δΈ€δΈͺ
                    ans += 1
                else:
                    # εΎ…εŒΉι…ηš„ε·¦ζ‹¬ε·ε‡ 1
                    x -= 1
            i += 1
        # ιεŽ†η»“ζŸοΌŒδ»ζœ‰εΎ…εŒΉι…ηš„ε·¦ζ‹¬ε·οΌŒθ―΄ζ˜Žε³ζ‹¬ε·δΈθΆ³οΌŒζ’ε…₯ x << 1 δΈͺ
        ans += x << 1
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    public int minInsertions(String s) {
        int ans = 0, x = 0;
        int n = s.length();
        for (int i = 0; i < n; ++i) {
            if (s.charAt(i) == '(') {
                ++x;
            } else {
                if (i < n - 1 && s.charAt(i + 1) == ')') {
                    ++i;
                } else {
                    ++ans;
                }
                if (x == 0) {
                    ++ans;
                } else {
                    --x;
                }
            }
        }
        ans += x << 1;
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
    int minInsertions(string s) {
        int ans = 0, x = 0;
        int n = s.size();
        for (int i = 0; i < n; ++i) {
            if (s[i] == '(') {
                ++x;
            } else {
                if (i < n - 1 && s[i + 1] == ')') {
                    ++i;
                } else {
                    ++ans;
                }
                if (x == 0) {
                    ++ans;
                } else {
                    --x;
                }
            }
        }
        ans += x << 1;
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
func minInsertions(s string) int {
    ans, x, n := 0, 0, len(s)
    for i := 0; i < n; i++ {
        if s[i] == '(' {
            x++
        } else {
            if i < n-1 && s[i+1] == ')' {
                i++
            } else {
                ans++
            }
            if x == 0 {
                ans++
            } else {
                x--
            }
        }
    }
    ans += x << 1
    return ans
}

Comments