Статья пока доступна только на английском.
Problem Description
Write a function that checks whether a bracket sequence is valid.
Input: a string of brackets.
Output: a boolean.
Constraints
- The string contains from 1 to 104 characters
- The string consists only of the brackets
(,),[,],{,}
Examples
Input: ()
Answer: true
What makes a bracket sequence valid
A bracket sequence is valid if:
- Every opening bracket has a closing bracket
- Brackets are closed in the correct order (an opening bracket comes first, and only then the closing one)
- Every opening bracket is closed by the matching type of closing bracket
(->),[->],{->} - There are no closing brackets without a preceding opening one
Solution
This problem has a "canonical" optimal solution that is expected at any interview (although, of course, it's not the only correct one). It uses the stack data structure.
The algorithm:
- Create an empty stack (it can be implemented with a regular array)
- Iterate over the string character by character
- If we see one of the opening brackets
(,[,{, push it onto the stack - If we see one of the closing brackets
),],}:- Check whether the stack has elements. If it's empty, the sequence is invalid (there's no unclosed opening bracket before the closing one)
- If the stack is not empty, pop the top element and check that it matches the current closing bracket
)->(,]->[,}->{. If they don't match, the sequence is invalid.
- If the stack is empty after processing the whole string, the sequence is valid. If it's not empty, the string has opening brackets without a closing pair.
typescript
export const isValid = (brackets: string): boolean => {
const stack: string[] = [];
const closeBrackets: Record<string, string> = {
')': '(',
']': '[',
'}': '{',
};
for (let i = 0; i < brackets.length; i++) {
const char = brackets[i];
const openBracket = closeBrackets[char];
if (openBracket) {
if (stack.length === 0) {
return false;
}
const lastOpenBracket = stack[stack.length - 1];
if (lastOpenBracket !== openBracket) {
return false;
}
stack.pop();
} else {
stack.push(char);
}
}
return stack.length === 0;
};Complexity Analysis
Time Complexity
O(n), where n is the length of the string.
Space Complexity
O(n), since we need memory for the stack, which in the worst case is as long as the string.