2. Valid Parentheses
easyAsked at GitLabValidate that a string of brackets is properly nested and closed in order.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s containing only the characters '()[]{}', return true if every open bracket is closed by the matching type in the correct order, false otherwise.
Constraints
1 <= s.length <= 10^4s contains only bracket characters
Examples
Example 1
s="()[]{}"trueExample 2
s="(]"falseApproaches
1. Brute force replace
Repeatedly strip empty pairs until no change.
- Time
- O(n^2)
- Space
- O(n)
while (s.includes('()')||s.includes('[]')||s.includes('{}'))
s = s.replaceAll('()','').replaceAll('[]','').replaceAll('{}','');
return s.length===0;Tradeoff:
2. Stack
Push opens, pop on close and verify match.
- Time
- O(n)
- Space
- O(n)
function isValid(s){
const m={')':'(',']':'[','}':'{'};
const st=[];
for (const c of s){
if (c in m){
if (st.pop()!==m[c]) return false;
} else st.push(c);
}
return st.length===0;
}Tradeoff:
GitLab-specific tips
GitLab interviewers often follow up by asking how this would handle CI-pipeline YAML or markdown nesting — keep an extensible mapping in mind.
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 GitLab interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →