CodingEasy Searching & Stacks
Valid Parentheses
Asked for all developer roles
Why they ask this: The standard stack problem; it shows you can pick the right data structure for matching pairs.
Problem
Given a string s containing only the characters (, ), {, }, [ and ], return true if:
- every opening bracket is closed by the same type of bracket, and
- brackets are closed in the correct order.
Examples
text
Input: "()[]{}" Output: true
Input: "([{}])" Output: true
Input: "(]" Output: false
Input: "([)]" Output: false
Input: "((" Output: falseHints
Approach
Use a stack and a map from each closing bracket to its opening partner:
- For an opening bracket, push it.
- For a closing bracket, pop the top. If the stack was empty or the popped bracket is not the matching opener, return
false. - After the loop, return
trueonly if the stack is empty (otherwise some brackets were never closed).
Quick check: a string with an odd length can never be valid.
Solution
js
function isValid(s) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const ch of s) {
if (ch === '(' || ch === '[' || ch === '{') {
stack.push(ch);
} else if (stack.pop() !== pairs[ch]) {
return false;
}
}
return stack.length === 0;
}
console.log(isValid('([{}])')); // true
console.log(isValid('([)]')); // false Time
O(n) Space O(n)Can you explain this in your own words?