Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Valid Parentheses in an Expression
Next article icon

Check for balanced with only one type of brackets

Last Updated : 20 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string str of length N, consisting of '(' and ')' only, the task is to check whether it is balanced or not.
Examples:

Input: str = "((()))()()" 
Output: Balanced

Input: str = "())((())" 
Output: Not Balanced 


Approach 1: 

  • Declare a Flag variable which denotes expression is balanced or not.
  • Initialise Flag variable with true and Count variable with 0.
  • Traverse through the given expression
  • If we encounter an opening parentheses (, increase count by 1
  • If we encounter a closing parentheses ), decrease count by 1
  • If Count becomes negative at any point, then expression is said to be not balanced, 
    so mark Flag as false and break from loop.
  • After traversing the expression, if Count is not equal to 0, 
    it means the expression is not balanced so mark Flag as false.
  • Finally, if Flag is true, expression is balanced else not balanced.

Below is the implementation of the above approach:
 

C++
// C++ program for the above approach.  #include <bits/stdc++.h>  using namespace std;  // Function to check // if parentheses are balanced bool isBalanced(string exp) {      // Initialising Variables     bool flag = true;     int count = 0;      // Traversing the Expression     for (int i = 0; i < exp.length(); i++) {          if (exp[i] == '(') {             count++;         }         else {              // It is a closing parenthesis             count--;         }         if (count < 0) {              // This means there are             // more Closing parenthesis             // than opening ones             flag = false;             break;         }     }      // If count is not zero,     // It means there are     // more opening parenthesis     if (count != 0) {         flag = false;     }      return flag; }  // Driver code int main() {     string exp1 = "((()))()()";      if (isBalanced(exp1))         cout << "Balanced \n";     else         cout << "Not Balanced \n";      string exp2 = "())((())";      if (isBalanced(exp2))         cout << "Balanced \n";     else         cout << "Not Balanced \n";      return 0; } 
C
// C program of the above approach #include <stdbool.h>  #include <stdio.h>  // Function to check if // parentheses are balanced bool isBalanced(char exp[]) {     // Initialising Variables     bool flag = true;     int count = 0;      // Traversing the Expression     for (int i = 0; exp[i] != '\0'; i++) {          if (exp[i] == '(') {             count++;         }         else {             // It is a closing parenthesis             count--;         }         if (count < 0) {             // This means there are             // more Closing parenthesis             // than opening ones             flag = false;             break;         }     }      // If count is not zero,     // It means there are more     // opening parenthesis     if (count != 0) {         flag = false;     }      return flag; }  // Driver code int main() {     char exp1[] = "((()))()()";      if (isBalanced(exp1))         printf("Balanced \n");     else         printf("Not Balanced \n");      char exp2[] = "())((())";      if (isBalanced(exp2))         printf("Balanced \n");     else         printf("Not Balanced \n");      return 0; } 
Java
// Java program for the above approach.  class GFG{  // Function to check  // if parentheses are balanced  public static boolean isBalanced(String exp)  {          // Initialising variables      boolean flag = true;      int count = 0;           // Traversing the expression      for(int i = 0; i < exp.length(); i++)     {          if (exp.charAt(i) == '(')          {              count++;          }          else         {                           // It is a closing parenthesis              count--;          }          if (count < 0)         {                           // This means there are              // more Closing parenthesis              // than opening ones              flag = false;              break;          }      }           // If count is not zero,      // It means there are      // more opening parenthesis      if (count != 0)      {          flag = false;      }     return flag;  }   // Driver code public static void main(String[] args) {     String exp1 = "((()))()()";           if (isBalanced(exp1))          System.out.println("Balanced");     else         System.out.println("Not Balanced");          String exp2 = "())((())";           if (isBalanced(exp2))          System.out.println("Balanced");     else         System.out.println("Not Balanced"); } }  // This code is contributed by divyeshrabadiya07 
Python3
# Python3 program for the above approach  # Function to check if  # parenthesis are balanced def isBalanced(exp):      # Initialising Variables     flag = True     count = 0      # Traversing the Expression     for i in range(len(exp)):         if (exp[i] == '('):             count += 1         else:                          # It is a closing parenthesis             count -= 1          if (count < 0):              # This means there are              # more closing parenthesis              # than opening             flag = False             break      # If count is not zero ,      # it means there are more      # opening parenthesis     if (count != 0):         flag = False      return flag  # Driver code if __name__ == '__main__':           exp1 = "((()))()()"      if (isBalanced(exp1)):         print("Balanced")     else:         print("Not Balanced")      exp2 = "())((())"      if (isBalanced(exp2)):         print("Balanced")     else:         print("Not Balanced")  # This code is contributed by himanshu77 
C#
// C# program for the above approach.  using System;  class GFG{  // Function to check  // if parentheses are balanced  public static bool isBalanced(String exp)  {          // Initialising variables      bool flag = true;      int count = 0;           // Traversing the expression      for(int i = 0; i < exp.Length; i++)     {          if (exp[i] == '(')          {              count++;          }          else         {                           // It is a closing parenthesis              count--;          }          if (count < 0)         {                           // This means there are              // more Closing parenthesis              // than opening ones              flag = false;              break;          }      }           // If count is not zero,      // It means there are      // more opening parenthesis      if (count != 0)      {          flag = false;      }     return flag;  }   // Driver code public static void Main(String[] args) {     String exp1 = "((()))()()";           if (isBalanced(exp1))          Console.WriteLine("Balanced");     else         Console.WriteLine("Not Balanced");          String exp2 = "())((())";           if (isBalanced(exp2))          Console.WriteLine("Balanced");     else         Console.WriteLine("Not Balanced"); } }  // This code is contributed by Amit Katiyar  
JavaScript
<script>  // JavaScript program for the above approach  // Function to check if  // parenthesis are balanced function isBalanced(exp){      // Initialising Variables     let flag = true     let count = 0      // Traversing the Expression     for(let i=0;i<exp.length;i++){         if (exp[i] == '(')             count += 1         else                          // It is a closing parenthesis             count -= 1          if (count < 0){              // This means there are              // more closing parenthesis              // than opening             flag = false             break         }     }     // If count is not zero ,      // it means there are more      // opening parenthesis     if (count != 0)         flag = false      return flag }  // Driver code      let exp1 = "((()))()()"  if (isBalanced(exp1))     document.write("Balanced","</br>") else     document.write("Not Balanced","</br>")  let exp2 = "())((())"  if (isBalanced(exp2))     document.write("Balanced","</br>") else     document.write("Not Balanced","</br>")  // This code is contributed by shinjanpatra  </script> 

Output
Balanced  Not Balanced 

Time complexity: O(N) 
Auxiliary Space: O(1)

Approach 2: Using Stack

  • Declare stack.
  • Iterate string using for loop charAt() method.
  • If it is an opening bracket then push it to stack
  • else if it is closing bracket and stack is empty then return 0.
  • else continue iterating till the end of the string.
  • at every step check top element of stack using peek() and pop() element accordingly
  • end loop
C++
// Here's the equivalent code in C++ with comments:  #include <iostream> #include <stack> using namespace std;  // function to check if the parentheses in a string are // balanced int check(string str) {     stack<char> s;     for (int i = 0; i < str.length(); i++) {         char c = str[i];         if (c == '(') {             s.push('(');         }         else if (c == ')') {             if (s.empty()) {                 return 0;             }             else {                 char p = s.top();                 if (p == '(') {                     s.pop();                 }                 else {                     return 0;                 }             }         }     }     if (s.empty()) {         return 1;     }     else {         return 0;     } }  int main() {     string str = "()(())()";     if (check(str) == 0) {         cout << "Invalid" << endl;     }     else {         cout << "Valid" << endl;     }     return 0; } 
Java
import java.util.*; public class Test {      public static int check(String str)     {         Stack<Character> s = new Stack();         for (int i = 0; i < str.length(); i++) {             char c = str.charAt(i);             if (c == '(') {                 s.push('(');             }             else if (c == ')') {                 if (s.isEmpty()) {                     return 0;                 }                 else {                     char p = s.peek();                     if (p == '(') {                         s.pop();                     }                     else {                         return 0;                     }                 }             }         }         if (s.empty()) {             return 1;         }         else {             return 0;         }     }      public static void main(String[] args)     {         String str = "()(())()";         if (check(str) == 0) {             System.out.println("Invalid");         }         else {             System.out.println("Valid");         }     } } 
Python
# Function to check if the parentheses in a string are balanced def check(str):     s = []     for c in str:         if c == '(':             s.append('(')         elif c == ')':             if len(s) == 0:                 return 0             else:                 p = s[-1]                 if p == '(':                     s.pop()                 else:                     return 0     if len(s) == 0:         return 1     else:         return 0   str = "()(())()" if check(str) == 0:     print("Invalid") else:     print("Valid") 
C#
using System; using System.Collections.Generic;  public class Program{   // Function to check if a given string of parentheses is balanced or not   public static int check(string str){     Stack<char> s = new Stack<char>();     for (int i = 0; i < str.Length; i++){       char c = str[i];       if (c == '('){         s.Push('(');       }       else if (c == ')'){         if (s.Count == 0){           return 0;         }         else{           char p = s.Peek();           if (p == '('){             s.Pop();           }           else{             return 0;           }         }       }     }     if (s.Count == 0){       return 1;     }     else{       return 0;     }   }    public static void Main(string[] args){     string str = "()(())()";     if (check(str) == 0){       Console.WriteLine("Invalid");     }     else{       Console.WriteLine("Valid");     }   } } 
JavaScript
// Function to check if the parentheses in a string are balanced function check(str) {     let s = [];     for (let i = 0; i < str.length; i++) {         let c = str[i];         if (c === '(') {             s.push('(');         } else if (c === ')') {             if (s.length === 0) {                 return 0;             } else {                 let p = s[s.length - 1];                 if (p === '(') {                     s.pop();                 } else {                     return 0;                 }             }         }     }     if (s.length === 0) {         return 1;     } else {         return 0;     } }  let str = "()(())()"; if (check(str) === 0) {     console.log("Invalid"); } else {     console.log("Valid"); } 

Output
Valid

Time complexity: O(N) 
Auxiliary Space: O(1)


Next Article
Valid Parentheses in an Expression
author
7maestro
Improve
Article Tags :
  • Strings
  • Competitive Programming
  • C++ Programs
  • C Language
  • C++
  • DSA
Practice Tags :
  • CPP
  • Strings

Similar Reads

    Mastering Bracket Problems for Competitive Programming
    Bracket problems in programming typically refer to problems that involve working with parentheses, and/or braces in expressions or sequences. It typically refers to problems related to the correct and balanced usage of parentheses, and braces in expressions or code. These problems often involve chec
    4 min read
    Check for balanced with only one type of brackets
    Given a string str of length N, consisting of '(' and ')' only, the task is to check whether it is balanced or not.Examples:Input: str = "((()))()()" Output: BalancedInput: str = "())((())" Output: Not Balanced Approach 1: Declare a Flag variable which denotes expression is balanced or not.Initialis
    9 min read
    Valid Parentheses in an Expression
    Given a string s representing an expression containing various types of brackets: {}, (), and [], the task is to determine whether the brackets in the expression are balanced or not. A balanced expression is one where every opening bracket has a corresponding closing bracket in the correct order.Exa
    8 min read
    Length of longest balanced parentheses prefix
    Given a string of open bracket '(' and closed bracket ')'. The task is to find the length of longest balanced prefix. Examples: Input : S = "((()())())((" Output : 10From index 0 to index 9, they are forming a balanced parentheses prefix.Input : S = "()(())((()"Output : 6The idea is take value of op
    9 min read
    Modify a numeric string to a balanced parentheses by replacements
    Given a numeric string S made up of characters '1', '2' and '3' only, the task is to replace characters with either an open bracket ( '(' ) or a closed bracket ( ')' ) such that the newly formed string becomes a balanced bracket sequence. Note: All occurrences of a character must be replaced by the
    10 min read
    Check if the bracket sequence can be balanced with at most one change in the position of a bracket
    Given an unbalanced bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = ")(()" Output: Yes As by moving s[0] to the end will make it valid. "(
    6 min read
    Number of closing brackets needed to complete a regular bracket sequence
    Given an incomplete bracket sequence S. The task is to find the number of closing brackets ')' needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete th
    7 min read
    Minimum number of Parentheses to be added to make it valid
    Given a string S of parentheses '(' or ')' where, 0\leq len(S)\leq 1000 . The task is to find a minimum number of parentheses '(' or ')' (at any positions) we must add to make the resulting parentheses string is valid. Examples: Input: str = "())" Output: 1 One '(' is required at beginning. Input: s
    9 min read
    Minimum bracket reversals to make an expression balanced
    Given an expression with only '}' and '{'. The expression may not be balanced. Find minimum number of bracket reversals to make the expression balanced.Examples: Input: s = "}{{}}{{{"Output: 3Explanation: We need to reverse minimum 3 brackets to make "{{{}}{}}". Input: s = "{{"Output: 1Explanation:
    15+ min read
    Find the number of valid parentheses expressions of given length
    Given a number n, the task is to find the number of valid parentheses expressions of that length. Examples : Input: 2Output: 1 Explanation: There is only possible valid expression of length 2, "()"Input: 4Output: 2 Explanation: Possible valid expression of length 4 are "(())" and "()()" Input: 6Outp
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences