Leetcode 1541: Minimum Insertions to Balance a Parentheses String

grid47
grid47
Exploring patterns and algorithms
Jun 5, 2024 5 min read

You are given a string s containing only the characters '(' and ')'. A string is considered balanced if each '(' has a matching pair of consecutive '))' and if they appear in the correct order. Your task is to return the minimum number of insertions needed to make the string balanced.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `s` containing only `'('` and `')'.
Example: s = '(()))'
Constraints:
• 1 <= s.length <= 10^5
• s consists only of the characters '(' and ')'.
Output: Return the minimum number of insertions required to make the string balanced.
Example: Output: 1
Constraints:
• The string can be balanced by inserting characters anywhere in the string.
Goal: The goal is to determine how many insertions are needed to balance the string.
Steps:
• 1. Traverse through the string and use a stack to keep track of unmatched parentheses.
• 2. For every closing parenthesis, try to match it with an opening parenthesis.
• 3. If there is no match, determine how many insertions are required to balance the string.
Goal: The string length should be within the given range and consist only of `(` and `)` characters.
Steps:
• 1 <= s.length <= 10^5
• s consists of '(' and ')'.
Assumptions:
• The string is only composed of characters '(' and ')'.
• The string can be unbalanced and requires insertions to be fixed.
Input: s = '(()))'
Explanation: The first '(' requires one more ')' to balance the string. We add one more ')' to get '(())))'.

Input: s = '()))'
Explanation: No insertions are needed because the string is already balanced.

Input: s = '))())('
Explanation: We need to add one '(' to match the first two closing parentheses and one '))' to match the last '('.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus