Leetcode 921: Minimum Add to Make Parentheses Valid

grid47
grid47
Exploring patterns and algorithms
Aug 6, 2024 5 min read

You are given a string consisting of parentheses. In one move, you can insert a parenthesis (either ‘(’ or ‘)’) at any position in the string. Your task is to return the minimum number of moves required to make the string valid, meaning all parentheses are properly balanced.
Problem
Approach
Steps
Complexity
Input: The input consists of a string of parentheses, with each character being either '(' or ')'.
Example: Input: s = "(()))"
Constraints:
• 1 <= s.length <= 1000
• Each character in s is either '(' or ')'.
Output: The output should be an integer representing the minimum number of moves required to make the parentheses string valid.
Example: Output: 1
Constraints:
• The string will contain only '(' and ')'.
Goal: The goal is to calculate how many parentheses need to be added in order to balance the string.
Steps:
• Traverse through the string character by character.
• Use a stack to keep track of unmatched opening parentheses '('.
• For each closing parenthesis ')', pop from the stack if there is a matching opening parenthesis, otherwise count it as a required move.
• At the end, the stack will contain unmatched opening parentheses, and the number of required moves will be equal to the size of the stack.
Goal: Ensure that the input string satisfies the constraints for length and valid parentheses.
Steps:
• The input string will be between 1 and 1000 characters long.
• Each character in the input string will be either '(' or ')'.
Assumptions:
• The input string contains only parentheses.
Input: Input: s = "())"
Explanation: The string has one unmatched closing parenthesis. To balance it, we need to insert one opening parenthesis at the beginning. So, the answer is 1.

Input: Input: s = "((("
Explanation: The string has three unmatched opening parentheses. To balance it, we need to insert three closing parentheses at the end. So, the answer is 3.

Link to LeetCode Lab


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