Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. 3. Every close bracket has a corresponding open bracket of the same type. **Examples:** ```typescript isValid("()") // true isValid("()[]{}") // true isValid("(]") // false ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(n)
- Space complexity: O(n)
We traverse the string exactly once. Operations on the stack (push and pop) take O(1) time. Thus, checking n characters takes O(n) linear time.
Follow-Up Questions Interviewers Ask About Valid Parentheses
- What data structure is ideal for tracking nested or LIFO relationships and why?
A Stack. Because a closing bracket must match the most recently encountered opening bracket, the Last-In-First-Out (LIFO) property of a stack makes it the ideal data structure. - If you only had parentheses () and no other bracket types, could you solve this in O(1) space?
Yes! Instead of a stack, maintain an integer counter: increment for "(" and decrement for ")". If the counter ever drops below 0, return false immediately. At the end, return counter === 0. - How would you adapt this to ignore non-bracket characters in mathematical expressions?
Filter or skip characters that are not part of your bracket map or opening set (e.g. check if char in map or opening set) and only push/pop valid bracket tokens.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.