Stack Easy
Valid Parentheses: Solution and Approach
Given a string of the brackets ( ) { } [ ], return true if every opening bracket is closed by the same type in the correct order.
Similar questions reported in: TCS, Infosys, Wipro, Accenture, Amazon, Cognizant
Example
- Input:
- s = "([]{})"
- Output:
- true
Brute force first
Repeatedly remove "()", "[]" and "{}" until nothing changes. This is O(n²).
The better idea
Use a stack. Push every opening bracket. For a closing bracket, the top of the stack must be its matching opener. At the end the stack must be empty.
Steps
- Map each closing bracket to its opener: ) → (, ] → [, } → {.
- For each character: if it is an opener, push it.
- If it is a closer, and the stack is empty or the top doesn't match, return false. Otherwise pop.
- Return true only if the stack is empty.
Code
def is_valid(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in pairs:
if not stack or stack[-1] != pairs[ch]:
return False
stack.pop()
else:
stack.append(ch)
return not stackpublic boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char ch : s.toCharArray()) {
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
} else {
if (stack.isEmpty()) return false;
char open = stack.pop();
if ((ch == ')' && open != '(') || (ch == ']' && open != '[') || (ch == '}' && open != '{')) {
return false;
}
}
}
return stack.isEmpty();
}Complexity
Time: O(n)
Space: O(n) for the stack.
Edge cases to test
- Only openers, such as "((": the stack is not empty, so false.
- A closer first, such as ")(": the stack is empty, so false.
Solved it? Pick the next problem
Do one more problem from the same pattern today, so the idea sticks.