Explorer
JavaScript

Write a function `isValidBrackets(str)` that checks if the brackets in the string are correctly matched. Handle (), [], {}.

Problem Statement

<p>Write a function <code>isValidBrackets(str)</code> that checks if the brackets in the string are correctly matched. Handle (), [], {}.</p>

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

šŸ’” Hint 1: Use a stack (array). Push opening brackets, pop for closing brackets. šŸ’” Hint 2: When encountering a closing bracket, the top of the stack must be the matching opening bracket. šŸ’” Hint 3: Use a Map to define bracket pairs: {"(":")", "[":"]", "{":"}"}.

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

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (use a stack (array). push opening brackets, pop for closing brackets).
  3. Implement Logic: Handle state and transformations efficiently (when encountering a closing bracket, the top of the stack must be the matching opening bracket).
  4. 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

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

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.

Valid Brackets

Medium

Write a function isValidBrackets(str) that checks if the brackets in the string are correctly matched. Handle (), [], {}.

Example Scenarios
1Example 1
Input: str = "()[]{}"
Output: true
Explanation:

Brackets are correctly matched and closed.

2Example 2
Input: str = "(]"
Output: false
Explanation:

Mismatched closing bracket.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[true,false,true,false]