Valid Parentheses in an Expression
Last Updated :
13 Jan, 2025
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.
Example:
Input: s = "[{()}]"
Output: true
Explanation: All the brackets are well-formed.
Input: s = "[()()]{}"
Output: true
Explanation: All the brackets are well-formed.
Input: s = "([]"
Output: false
Explanation: The expression is not balanced as there is a missing ')' at the end.
Input: s = "([{]})"
Output: false
Explanation: The expression is not balanced because there is a closing ']' before the closing '}'.
[Expected Approach 1] Using Stack - O(n) Time and O(n) Space
The idea is to put all the opening brackets in the stack. Whenever you hit a closing bracket, search if the top of the stack is the opening bracket of the same nature. If this holds then pop the stack and continue the iteration. In the end if the stack is empty, it means all brackets are balanced or well-formed. Otherwise, they are not balanced.
Step-by-step approach:
- Declare a character stack (say temp).
- Now traverse the string s.
- If the current character is an opening bracket ( '(' or '{' or '[' ) then push it to stack.
- If the current character is a closing bracket ( ')' or '}' or ']' ) and the closing bracket matches with the opening bracket at the top of stack, then pop the opening bracket. Else s is not balanced.
- After complete traversal, if some starting brackets are left in the stack then the expression is not balanced, else balanced.
Illustration:
C++
// C++ program to check if parentheses are balanced
#include <bits/stdc++.h>
using namespace std;
bool isBalanced(const string& s) {
// Declare a stack to store the opening brackets
stack<char> st;
for (int i = 0; i < s.length(); i++) {
// Check if the character is an opening bracket
if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
st.push(s[i]);
}
else {
// If it's a closing bracket, check if the stack is non-empty
// and if the top of the stack is a matching opening bracket
if (!st.empty() &&
((st.top() == '(' && s[i] == ')') ||
(st.top() == '{' && s[i] == '}') ||
(st.top() == '[' && s[i] == ']'))) {
// Pop the matching opening bracket
st.pop();
}
else {
// Unmatched closing bracket
return false;
}
}
}
// If stack is empty, return true (balanced), otherwise false
return st.empty();
}
int main() {
string s = "{([])}";
if (isBalanced(s))
cout << "true";
else
cout << "false";
return 0;
}
Java
// Java program to check if parentheses are balanced
import java.util.Stack;
class GfG {
static boolean isBalanced(String s) {
// Declare a stack to store the opening brackets
Stack<Character> st = new Stack<>();
for (int i = 0; i < s.length(); i++) {
// Check if the character is an opening bracket
if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
st.push(s.charAt(i));
}
else {
// If it's a closing bracket, check if the stack is non-empty
// and if the top of the stack is a matching opening bracket
if (!st.empty() &&
((st.peek() == '(' && s.charAt(i) == ')') ||
(st.peek() == '{' && s.charAt(i) == '}') ||
(st.peek() == '[' && s.charAt(i) == ']'))) {
st.pop();
}
else {
// Unmatched closing bracket
return false;
}
}
}
// If stack is empty, return true (balanced),
// otherwise false
return st.empty();
}
public static void main(String[] args) {
String s = "{([])}";
if (isBalanced(s))
System.out.println("true");
else
System.out.println("false");
}
}
Python
# Python program to check if parentheses are balanced
def isBalanced(s):
# Declare a stack to store the opening brackets
st = []
for i in range(len(s)):
# Check if the character is an opening bracket
if s[i] == '(' or s[i] == '{' or s[i] == '[':
st.append(s[i])
else:
# If it's a closing bracket, check if the stack is non-empty
# and if the top of the stack is a matching opening bracket
if st and ((st[-1] == '(' and s[i] == ')') or
(st[-1] == '{' and s[i] == '}') or
(st[-1] == '[' and s[i] == ']')):
# Pop the matching opening bracket
st.pop()
else:
# Unmatched closing bracket
return False
# If stack is empty, return True (balanced), otherwise False
return not st
if __name__ == "__main__":
s = "{([])}"
if isBalanced(s):
print("true")
else:
print("false")
C#
// C# program to check if parentheses are balanced
using System;
using System.Collections.Generic;
class GfG {
static bool isBalanced(string s) {
// Declare a stack to store the opening brackets
Stack<char> st = new Stack<char>();
for (int i = 0; i < s.Length; i++) {
// Check if the character is an opening bracket
if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
st.Push(s[i]);
}
else {
// If it's a closing bracket, check if the stack is non-empty
// and if the top of the stack is a matching opening bracket
if (st.Count > 0 &&
((st.Peek() == '(' && s[i] == ')') ||
(st.Peek() == '{' && s[i] == '}') ||
(st.Peek() == '[' && s[i] == ']'))) {
st.Pop();
}
else {
// Unmatched closing bracket
return false;
}
}
}
// If stack is empty, return true (balanced),
// otherwise false
return st.Count == 0;
}
public static void Main(string[] args) {
string s = "{([])}";
if (isBalanced(s))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
JavaScript
// Javascript program to check if parentheses are balanced
function isBalanced(s) {
// Declare a stack to store the opening brackets
let st = [];
for (let i = 0; i < s.length; i++) {
// Check if the character is an opening bracket
if (s[i] === '(' || s[i] === '{' || s[i] === '[') {
st.push(s[i]);
} else {
// If it's a closing bracket, check if the stack is non-empty
// and if the top of the stack is a matching opening bracket
if (st.length > 0 &&
((st[st.length - 1] === '(' && s[i] === ')') ||
(st[st.length - 1] === '{' && s[i] === '}') ||
(st[st.length - 1] === '[' && s[i] === ']'))) {
// Pop the matching opening bracket
st.pop();
} else {
// Unmatched closing bracket
return false;
}
}
}
// If stack is empty, return true (balanced), otherwise false
return st.length === 0;
}
// Driver Code
let s = "{([])}";
console.log(isBalanced(s) ? "true" : "false");
[Expected Approach 2] Without using Stack - O(n) Time and O(1) Space
Instead of using actual Stack, we can uses the input string s itself to simulate stack behavior. We can use a top variable to keep track of the "top" of this virtual stack. This approach makes use of the existing string to avoid the need for additional memory to store stack elements.
Note: Strings are immutable in Java, Python, C#, and JavaScript. Therefore, we cannot modify them in place, making this approach unsuitable for these languages.
Step-by-Step approach:
- Initialize top = -1 to represent an empty stack.
- Traverse over the given string and for each character:
- If top is -1 or the current character doesn’t match the top, increment top and store the character at s[top].
- If the current character matches s[top], decrement top to remove the last unmatched opening parenthesis.
- After processing, if top is -1, the string is balanced. Otherwise, it is unbalanced.
C++
// C++ program to check if parentheses are balanced
#include <bits/stdc++.h>
using namespace std;
// Check if characters match
bool checkMatch(char c1, char c2){
if (c1 == '(' && c2 == ')') return true;
if (c1 == '[' && c2 == ']') return true;
if (c1 == '{' && c2 == '}') return true;
return false;
}
// Check if parentheses are balanced
bool isBalanced(string& s){
// Initialize top to -1
int top = -1;
for (int i = 0; i < s.length(); ++i){
// Push char if stack is empty or no match
if (top < 0 || !checkMatch(s[top], s[i])){
++top;
s[top] = s[i];
}
else{
// Pop from stack if match found
--top;
}
}
// Return true if stack is empty (balanced)
return top == -1;
}
int main(){
string s = "{([])}";
cout << (isBalanced(s) ? "true" : "false") << endl;
return 0;
}
C
// C program to check if parentheses are balanced
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
// Check if characters match
bool checkMatch(char c1, char c2){
if (c1 == '(' && c2 == ')') return true;
if (c1 == '[' && c2 == ']') return true;
if (c1 == '{' && c2 == '}') return true;
return false;
}
// Check if parentheses are balanced
bool isBalanced(char s[]){
// Initialize top as -1 (empty stack simulation)
int top = -1;
for (int i = 0; i < strlen(s); ++i){
// Push char if stack is empty or no match
if (top < 0 || !checkMatch(s[top], s[i])){
++top;
s[top] = s[i];
}
else{
// Pop from stack if match found
--top;
}
}
// Return true if stack is empty (balanced)
return top == -1;
}
int main(){
char s[] = "{([])}";
printf("%s\n", isBalanced(s) ? "true" : "false");
return 0;
}
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