Given string str containing just the characters '(', ')', '{', '}', '[' and ']', check if the input string is valid and return true if the string is balanced otherwise return false.
Input: str = “()[{}()]”
Output: True
Explanation: As every open bracket has its corresponding close bracket. Match parentheses are in correct order hence they are balanced.
Input: str = “[()”
Output: False
Explanation: As ‘[‘ does not have ‘]’ hence it is not valid and will return false.
Input: str = "{[()]}"
1 <= str.length <= 104
str consists of parentheses only '()[]{}'.
Let us understand first when a string is said to be balanced:
What if there is no top element in stack when a closing bracket is found?
This will happen for strings like "()]", where there is no opening bracket to compare with the ']' bracket. In such cases, the parantheis will be invalid.
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
/* Function to match the opening
and closing brackets */
bool isMatched(char open, char close) {
// Match
if((open == '(' && close == ')') ||
(open == '[' && close == ']') ||
(open == '{' && close == '}')
)
return true;
// Mismatch
return false;
}
public:
/* Function to check if the
string is valid */
bool isValid(string str) {
// Initialize a stack
stack<char> st;
// Start iterating on the string
for(int i=0; i < str.length(); i++) {
// If an opening bracket is found
if(str[i] == '(' || str[i] == '[' ||
str[i] == '{') {
// Push on top of stack
st.push(str[i]);
}
// Else if a closing bracket is found
else {
// Return false if stack is empty
if(st.empty()) return false;
// Get the top elemenfrom stack
char ch = st.top();
st.pop();
/* If the opening and closing brackets
are not matched, return false */
if(!isMatched(ch, str[i]))
return false;
}
}
/* If stack is empty, the
string is valid, else invalid */
return st.empty();
}
};
int main() {
string str = "()[{}()]";
/* Creating an instance of
Solution class */
Solution sol;
/* Function call to check if the
string is valid */
bool ans = sol.isValid(str);
if(ans)
cout << "The given string is valid.";
else
cout << "The given string is invalid.";
return 0;
}
import java.util.Stack;
class Solution {
/* Function to match the opening
and closing brackets */
private boolean isMatched(char open, char close) {
// Match
if((open == '(' && close == ')') ||
(open == '[' && close == ']') ||
(open == '{' && close == '}')
)
return true;
// Mismatch
return false;
}
/* Function to check if the
string is valid */
public boolean isValid(String str) {
// Initialize a stack
Stack<Character> st = new Stack<>();
// Start iterating on the string
for(int i=0; i < str.length(); i++) {
// If an opening bracket is found
if(str.charAt(i) == '(' || str.charAt(i) == '[' ||
str.charAt(i) == '{') {
// Push on top of stack
st.push(str.charAt(i));
}
// Else if a closing bracket is found
else {
// Return false if stack is empty
if(st.isEmpty()) return false;
// Get the top element from stack
char ch = st.peek();
st.pop();
/* If the opening and closing brackets
are not matched, return false */
if(!isMatched(ch, str.charAt(i))) return false;
}
}
/* If stack is empty, the
string is valid, else invalid */
return st.isEmpty();
}
public static void main(String[] args) {
String str = "()[{}()]";
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function call to check if the
string is valid */
boolean ans = sol.isValid(str);
if(ans)
System.out.println("The given string is valid.");
else
System.out.println("The given string is invalid.");
}
}
class Solution:
# Function to match the opening
# and closing brackets
def isMatched(self, open, close):
# Match
if((open == '(' and close == ')') or
(open == '[' and close == ']') or
(open == '{' and close == '}')
):
return True
# Mismatch
return False
# Function to check if the
# string is valid
def isValid(self, str):
# Initialize a stack
st = []
# Start iterating on the string
for i in range(len(str)):
# If an opening bracket is found
if str[i] == '(' or str[i] == '[' or str[i] == '{':
# Push on top of stack
st.append(str[i])
# Else if a closing bracket is found
else:
# Return false if stack is empty
if not st:
return False
# Get the top element from stack
ch = st[-1]
st.pop()
# If the opening and closing brackets
# are not matched, return false
if not self.isMatched(ch, str[i]):
return False
# If stack is empty, the
# string is valid, else invalid
return not st
# Creating an instance of
# Solution class
sol = Solution()
# Function call to check if the
# string is valid
str = "()[{}()]"
ans = sol.isValid(str)
if ans:
print("The given string is valid.")
else:
print("The given string is invalid.")
class Solution {
/* Function to match the opening
and closing brackets */
isMatched(open, close) {
// Match
if((open === '(' && close === ')') ||
(open === '[' && close === ']') ||
(open === '{' && close === '}')
)
return true;
// Mismatch
return false;
}
/* Function to check if the
string is valid */
isValid(str) {
// Initialize a stack
let st = [];
// Start iterating on the string
for(let i = 0; i < str.length; i++) {
// If an opening bracket is found
if(str[i] === '(' || str[i] === '[' ||
str[i] === '{') {
// Push on top of stack
st.push(str[i]);
}
// Else if a closing bracket is found
else {
// Return false if stack is empty
if(st.length === 0) return false;
// Get the top element from stack
let ch = st[st.length - 1];
st.pop();
/* If the opening and closing brackets
are not matched, return false */
if(!this.isMatched(ch, str[i])) return false;
}
}
/* If stack is empty, the
string is valid, else invalid */
return st.length === 0;
}
}
/* Creating an instance of
Solution class */
let sol = new Solution();
/* Function call to check if the
string is valid */
let str = "()[{}()]";
let ans = sol.isValid(str);
if(ans)
console.log("The given string is valid.");
else
console.log("The given string is invalid.");
Time Complexity: O(N) (where N is the length of the string)
Traversing the string once takes O(N) time.
Space Complexity: O(N)
In the worst case (when the string contains only opening brackets), the stack will store all the characters, taking O(N) space.
Q: Can there be interleaved brackets?
A: Yes, valid strings can have nested and interleaved brackets, like {[()()]}. The stack ensures the correct closing order by matching the last opened bracket first.
Q: What if the string contains non-bracket characters?
A: If only brackets are allowed, ignore any additional characters in preprocessing. If mixed characters are allowed, the logic should be applied only to bracket characters.
Q: How would you modify this for different types of brackets (e.g., < and >)?
A: Extend the bracket pair mapping { "(": ")", "{": "}", "[": "]", "<": ">" } to include the new bracket type.