1541. Minimum Insertions to Balance a Parentheses String
</> Solution
/**
* Problem: LeetCode 1541 - Minimum Insertions to Balance a Parentheses String
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int minInsertions(String s) {
int open = 0; // unmatched '('
int ans = 0; // insertions
int i = 0, n = s.length();
while (i < n) {
if (s.charAt(i) == '(') {
open++;
i++;
} else {
// Need two consecutive ')'
if (i + 1 < n && s.charAt(i + 1) == ')') {
i += 2;
} else {
ans++; // insert missing ')'
i++;
}
if (open > 0) {
open--;
} else {
ans++; // insert missing '('
}
}
}
return ans + open * 2;
}
}
"""
Problem: LeetCode 1541 - Minimum Insertions to Balance a Parentheses String
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
class Solution:
def minInsertions(self, s: str) -> int:
open_count = 0 # unmatched '('
ans = 0 # insertions
i = 0
n = len(s)
while i < n:
if s[i] == '(':
open_count += 1
i += 1
else:
# Need two consecutive ')'
if i + 1 < n and s[i + 1] == ')':
i += 2
else:
ans += 1 # insert missing ')'
i += 1
if open_count > 0:
open_count -= 1
else:
ans += 1 # insert missing '('
return ans + open_count * 2
/**
* Problem: LeetCode 1541 - Minimum Insertions to Balance a Parentheses String
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <string>
using namespace std;
/**
* Problem: LeetCode 1541 - Minimum Insertions to Balance a Parentheses String
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
int minInsertions(string s) {
int open = 0; // unmatched '('
int ans = 0; // insertions
int i = 0, n = s.length();
while (i < n) {
if (s[i] == '(') {
open++;
i++;
} else {
// Need two consecutive ')'
if (i + 1 < n && s[i + 1] == ')') {
i += 2;
} else {
ans++; // insert missing ')'
i++;
}
if (open > 0) {
open--;
} else {
ans++; // insert missing '('
}
}
}
return ans + open * 2;
}
};
/**
* Problem: LeetCode 1541 - Minimum Insertions to Balance a Parentheses String
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var minInsertions = function(s) {
let open = 0; // unmatched '('
let ans = 0; // insertions
let i = 0;
const n = s.length;
while (i < n) {
if (s[i] === '(') {
open++;
i++;
} else {
// Need two consecutive ')'
if (i + 1 < n && s[i + 1] === ')') {
i += 2;
} else {
ans++; // insert missing ')'
i++;
}
if (open > 0) {
open--;
} else {
ans++; // insert missing '('
}
}
}
return ans + open * 2;
};