Valid Parantheses


Problem Statement

Given a string str containing just the characters ( , ) , { , } , [ and ], determine if the input string is valid.

An input string is valid if:

Examples
()[]{} Valid
(] Invalid
[() Invalid
[(]) Invalid
()[([]){}] Valid

Stack solution

Being a LIFO data structure, we can know which was the latest inserted element. We use this property to know if there was a matching opening brace last inserted for current closing brace

bool isValid(string str)
{
// Odd length strings are invalid
if (str.size() & 1) return false;
// Store opening brace symbol corresponding to each closing brace symbol
unordered_map<char, char> matchingOpeningBrace{
{')', '('},
{']', '['},
{'}', '{'},
};
stack<char> stk; // Stack which stores opening braces
for (char c : str) // Iterate over string characters
{
// Add opening brace into stack
if (c == '(' || c == '[' || c == '{') {
stk.push(c);
}
// At closing brace:
else if (c == ')' || c == ']' || c == '}') {
// Matching opening brace should exist at top of stack, else invalid
if (stk.empty() || stk.top() != matchingOpeningBrace[c]) {
return false;
}
// Clear out current formed bracket pair
stk.pop();
}
}
// All matching pairs would get cleared out and stack should be empty. Else invalid
return (stk.empty());
}

Time

We are iterating all string characters once, so \( O(n) \) time complexity

Space

At most, there would be \( n \) characters present inside stack. This would occur when all characters are opening braces. Hence, the space complexity is \( O(n) \)