Valid Parentheses - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

To determine whether a string of brackets is valid, we need to verify two things:

  • Every opening bracket ((, {, [) is eventually closed by a matching closing bracket.
  • The brackets close in the correct order β€” no overlaps or mismatched nesting.

We use a stack to track currently β€œopen” brackets, since the last bracket opened must always be the first one to close (LIFO order). Alongside it, we hold a mapping of closing to opening brackets: { ')': '(', '}': '{', ']': '[' }. This helps the algorithm instantly identify which opening type is expected when a closing bracket appears.

As we scan through the string:

  • When we see an opening bracket, we push it onto the stack. It stays there until a matching closing bracket appears later. The top of the stack always represents the most recent unclosed bracket.
  • When we see a closing bracket, we look at the top of the stack β€” the most recent opening.
    • If the stack is empty, there’s no opening bracket to match β€” the string becomes invalid immediately.
    • If the top doesn’t match the required opening bracket from our mapping, the pair is mismatched β€” invalid as well.
    • If it matches, we pop it off the stack β€” that bracket pair is now successfully closed.

After processing the entire string, we check the stack:

  • If the stack is empty, all brackets were properly opened and closed β€” the string is valid.
  • If anything remains, it means there are unclosed openings β€” the string is invalid.

Why this works: The stack mirrors the natural nesting structure of brackets β€” every new opening must be closed before earlier ones can close. The mapping ensures each closing bracket is checked against the correct type of opening. Together, they guarantee both pairing correctness and order consistency, catching every possible invalid pattern.

Time Complexity

Let n be the length of the input string. We scan the string exactly once, performing constant-time operations for each character β€” either a push or a pop from the stack, plus a constant-time lookup in the mapping. Therefore, the time complexity is O(n).

Space Complexity

The algorithm uses:

  • A stack to store not yet matched opening brackets during scanning. In the worst case, all characters are opening brackets, so the stack can grow up to size n.
  • A fixed bracketMap storing the three bracket pairs ({ ')': '(', '}': '{', ']': '[' }), which takes O(1) space.

Therefore, the total auxiliary space complexity is O(n) in the worst case.

Visucodize editorial solution titled JS Solution for LeetCode's Valid Parentheses coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/valid-parentheses.