Write a function `isValidBrackets(str)` that checks if the brackets in the string are correctly matched. Handle (), [], {}.
Problem Statement
Examples
Input: str = "()[]{}"
Output: true
Explanation: Brackets are correctly matched and closed.
Input: str = "(]"
Output: false
Explanation: Mismatched closing bracket.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Valid Brackets, we consider the execution characteristics of JavaScript engines. Write a function `isValidBrackets(str)` that checks if the brackets in the string are correctly matched. Handle (), [], {}. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (use a stack (array). push opening brackets, pop for closing brackets).
- Implement Logic: Handle state and transformations efficiently (when encountering a closing bracket, the top of the stack must be the matching opening bracket).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function isValidBrackets(str) {
const stack = [];
const map = {"(":")", "[":"]", "{":"}"};
for (const ch of str) {
if (map[ch]) { stack.push(map[ch]); }
else if (ch === ")" || ch === "]" || ch === "}") {
if (stack.pop() !== ch) return false;
}
}
return stack.length === 0;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.