2. Valid Parentheses
easyAsked at LyftValidate that bracket characters in a string close in the right order.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s containing just '()[]{}', determine if the input is valid. An input is valid if open brackets are closed by the same type and in the correct order.
Constraints
1 <= s.length <= 10^4s consists of parentheses only
Examples
Example 1
s = "()[]{}"trueExample 2
s = "(]"falseApproaches
1. Repeated replace
Strip matched pairs until no change; reject if non-empty.
- Time
- O(n^2)
- Space
- O(n)
while (s.includes('()')||s.includes('[]')||s.includes('{}'))
s = s.replace('()','').replace('[]','').replace('{}','');
return s === '';Tradeoff:
2. Stack
Push openers, pop on closer and check the match. O(n) one pass.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const stack = [];
const pair = { ')':'(', ']':'[', '}':'{' };
for (const c of s) {
if (c in pair) {
if (stack.pop() !== pair[c]) return false;
} else {
stack.push(c);
}
}
return stack.length === 0;
}Tradeoff:
Lyft-specific tips
Lyft engineers like to relate the stack pattern to balancing nested events in their ride-state machine; mention LIFO ordering explicitly.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Valid Parentheses and other Lyft interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →