2. Valid Parentheses
easyAsked at DigitalOceanValidate balanced brackets in a string — DigitalOcean uses this to check stack fluency that maps to config-file parsing in Terraform-driven droplet provisioning.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s containing only the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. Brackets must close in the correct order and be matched by the same type.
Constraints
1 <= s.length <= 10^4s consists only of bracket characters
Examples
Example 1
s="()[]{}"trueExample 2
s="(]"falseApproaches
1. Brute force replace
Repeatedly remove '()', '[]', '{}' until none remain.
- Time
- O(n^2)
- Space
- O(n)
while (s.includes('()')||s.includes('[]')||s.includes('{}'))
s = s.replace('()','').replace('[]','').replace('{}','');
return s.length===0;Tradeoff:
2. Stack
Push openers; on closer, pop and verify matching pair.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pair = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const c of s) {
if (!(c in pair)) stack.push(c);
else if (stack.pop() !== pair[c]) return false;
}
return stack.length === 0;
}Tradeoff:
DigitalOcean-specific tips
DigitalOcean engineers want to see you validate input robustly because invalid cloud-init payloads cause silent droplet provisioning failures.
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 DigitalOcean interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →