Validate whether brackets are properly nested
BloombergSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to use a stack data structure to maintain LIFO ordering for matching paired symbols within a string.
Problem Statement
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.
- Open brackets are closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Function Signature
def is_valid(s: str) -> bool:
Constraints
1 <= s.length <= 10^4sconsists of parentheses only:()[]{}
Examples
Example 1:
Input: s = "()[]{}"
Output: True
Example 2:
Input: s = "([)]"
Output: False
Example 3:
Input: s = "{[]}"
Output: True
Edge Cases
- Empty strings or strings with an odd length should be handled appropriately.
- Strings with only opening or only closing brackets.
Hints
Hint 1
Consider using a stack to keep track of the most recently opened brackets.
Hint 2
When you encounter a closing bracket, check if it matches the top element of the stack.
Hint 3
If the stack is empty or the top of the stack does not match the current closing bracket, the string is invalid.
Follow-up questions
- How would you modify your solution to support an unlimited variety of bracket types using a mapping dictionary?
- What is the time and space complexity of your solution, and can you optimize the space complexity if the string only contains one type of bracket?
- How would you adapt the algorithm to return the index of the first mismatch instead of a boolean?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.