Skip to content

921. Minimum Add to Make Parentheses Valid #683

Answered by kovatz
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to determine how many opening or closing parentheses need to be added to make the input string s valid. A valid string means that every opening parenthesis '(' has a corresponding closing parenthesis ')'.

We can solve this problem using a simple counter approach:

  • We use a variable balance to keep track of the current balance between opening and closing parentheses.
  • We use another variable additions to count the minimum number of parentheses required.

Approach:

  1. Loop through each character of the string s.
  2. If the character is '(', increment balance by 1.
  3. If the character is ')', decrement balance by 1:
    • If balance becomes negative, it means there are more closing parentheses than…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mah-shamim
Comment options

mah-shamim Oct 9, 2024
Maintainer Author

@kovatz
Comment options

kovatz Oct 9, 2024
Collaborator

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty hacktoberfest hacktoberfest hacktoberfest-accepted hacktoberfest accepted
2 participants