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
#include <stdbool.h>
#include <stdio.h>
bool isBalanced( char exp [])
{
bool flag = true ;
int count = 0;
for ( int i = 0; exp [i] != '\0' ; i++) {
if ( exp [i] == '(' ) {
count++;
}
else {
count--;
}
if (count < 0) {
flag = false ;
break ;
}
}
if (count != 0) {
flag = false ;
}
return flag;
}
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;
}
|
C++
#include <bits/stdc++.h>
using namespace std;
bool isBalanced(string exp )
{
bool flag = true ;
int count = 0;
for ( int i = 0; i < exp .length(); i++) {
if ( exp [i] == '(' ) {
count++;
}
else {
count--;
}
if (count < 0) {
flag = false ;
break ;
}
}
if (count != 0) {
flag = false ;
}
return flag;
}
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;
}
|
Java
class GFG{
public static boolean isBalanced(String exp)
{
boolean flag = true ;
int count = 0 ;
for ( int i = 0 ; i < exp.length(); i++)
{
if (exp.charAt(i) == '(' )
{
count++;
}
else
{
count--;
}
if (count < 0 )
{
flag = false ;
break ;
}
}
if (count != 0 )
{
flag = false ;
}
return flag;
}
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" );
}
}
|
Python3
def isBalanced(exp):
flag = True
count = 0
for i in range ( len (exp)):
if (exp[i] = = '(' ):
count + = 1
else :
count - = 1
if (count < 0 ):
flag = False
break
if (count ! = 0 ):
flag = False
return flag
if __name__ = = '__main__' :
exp1 = "((()))()()"
if (isBalanced(exp1)):
print ( "Balanced" )
else :
print ( "Not Balanced" )
exp2 = "())((())"
if (isBalanced(exp2)):
print ( "Balanced" )
else :
print ( "Not Balanced" )
|
C#
using System;
class GFG{
public static bool isBalanced(String exp)
{
bool flag = true ;
int count = 0;
for ( int i = 0; i < exp.Length; i++)
{
if (exp[i] == '(' )
{
count++;
}
else
{
count--;
}
if (count < 0)
{
flag = false ;
break ;
}
}
if (count != 0)
{
flag = false ;
}
return flag;
}
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" );
}
}
|
Javascript
<script>
function isBalanced(exp){
let flag = true
let count = 0
for (let i=0;i<exp.length;i++){
if (exp[i] == '(' )
count += 1
else
count -= 1
if (count < 0){
flag = false
break
}
}
if (count != 0)
flag = false
return flag
}
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>" )
</script>
|
OutputBalanced
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++
#include <iostream>
#include <stack>
using namespace std;
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" );
}
}
}
|
Python3
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{
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 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" );
}
|
Time complexity: O(N)
Auxiliary Space: O(1)