Solving Leetcode Interviews in Seconds with AI: Minimum Insertions to Balance a Parentheses String
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1541" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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.
Explanation
Here's the solution:
- Approach: Iterate through the string. Maintain a count of open parentheses needed and a count of unmatched right parentheses. If we encounter a '(', increment the open parentheses needed. If we encounter a ')', check if we can match it with an existing open parenthesis or if we need another ')'.
- Complexity: Time: O(n), Space: O(1)
Code
def min_insertions(s: str) -> int:
"""
Calculates the minimum number of insertions needed to balance a parentheses string.
Args:
s: The parentheses string.
Returns:
The minimum number of insertions needed.
"""
open_needed = 0
insertions = 0
i = 0
while i < len(s):
if s[i] == '(':
open_needed += 1
else:
if open_needed > 0:
open_needed -= 1
if i + 1 < len(s) and s[i + 1] == ')':
i += 1
else:
insertions += 1
else:
insertions += 1
if i + 1 < len(s) and s[i + 1] == ')':
i += 1
else:
insertions += 1
i += 1
insertions += 2 * open_needed
return insertions