VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-of-parentheses-to-be-added-to-make-it-valid/

⇱ Minimum Additions for Valid Parentheses - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Additions for Valid Parentheses

Last Updated : 13 Sep, 2025

Given a string s consisting of parentheses '(' and ')'. Find the minimum number of parentheses (either '(' or ')') that must be added at any positions to make the string s a valid parentheses string.

A string is valid if every opening parenthesis has a corresponding closing parenthesis and they are properly nested.

Examples:

Input: s = "(()("
Output: 2
Explanation: Two '(' are left unmatched, so we need two ')' to balance.

Input: s = ")))"
Output: 3
Explanation: Three '(' need to be added at the end to make the string valid.

[Approach 1] Using Stack - O(n) Time and O(n) Space

The idea is to use the concept of valid parentheses. For every opening parenthesis, a matching closing parenthesis will remove it from the stack. At the end, only the unmatched parentheses remain in the stack, and their count gives the number of insertions needed to make the string valid.

At the end of the string:

  • Every '(' left in the stack needs a ')' to become valid.
  • Every ')' left in the stack needs a '(' to become valid.

Hence, the minimum number of insertions needed = number of unmatched parentheses = stack size.


Output
2

[Approach 2] Using Counter / Balance Method - O(n) Time and O(1) Space

The idea is to track unmatched parentheses using counters instead of a stack. We keep a balance for unmatched '(' and a counter for unmatched ')'. Whenever balance goes negative, it means there is an extra closing parenthesis, so we increase the unmatched closing counter and reset balance. At the end, the total insertions required is the sum of remaining unmatched '(' and unmatched ')'.


Output
2

[Approach 3] Using Two-Pass Counting Method - O(n) Time and O(1) Space

The idea is to scan the string twice first left to right to count unmatched ')', then right to left to count unmatched '('. The sum of these two counts gives the minimum insertions needed to make the string valid.


Output
2
Comment
Article Tags: