Leetcode Problem 921. Minimum Add to Make Parentheses Valid

921. Minimum Add to Make Parentheses Valid

Leetcode Solutions

Balancing Parentheses

  1. Initialize a variable balance to 0 to keep track of the balance of parentheses.
  2. Initialize a variable moves to 0 to count the number of moves required.
  3. Iterate through each character in the string s. a. If the character is an opening parenthesis '(', increment balance. b. If the character is a closing parenthesis ')', decrement balance. c. If balance is negative, it means we have an unmatched closing parenthesis, so increment moves and reset balance to 0.
  4. After the iteration, if balance is positive, it means we have unmatched opening parentheses, so add balance to moves.
  5. Return moves as the minimum number of moves required to make the string valid.
UML Thumbnail

Stack-Based Parentheses Validation

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...