2. Valid Parentheses
easyAsked at MonzoValidate that a string of brackets is properly nested and closed.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if open brackets are closed by the same type of brackets and in the correct order.
Constraints
1 <= s.length <= 10^4s consists of parentheses only
Examples
Example 1
s = "()"trueExample 2
s = "(]"falseApproaches
1. Naive scan
Scan and try to match without state.
- Time
- O(n^2)
- Space
- O(1)
// Naive cannot track nesting; will fail on "([)]".Tradeoff:
2. Stack
Push openers; for closers verify the top matches.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pairs = { ')': '(', '}': '{', ']': '[' };
const stack = [];
for (const c of s) {
if ('({['.includes(c)) stack.push(c);
else if (stack.pop() !== pairs[c]) return false;
}
return stack.length === 0;
}Tradeoff:
Monzo-specific tips
Monzo expects you to think about malformed input — apply the same defensive instincts you would for ledger entries.
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 Monzo interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →