☰ All problems

Valid Parentheses

EasyStringStack

Before a code editor reformats a snippet, it checks that the snippet's brackets are balanced. You receive only the brackets, as a string s made of the six characters (, ), [, ], { and }.

Return true if the brackets are balanced and false otherwise. They are balanced when all of the following hold:

  • each closing bracket has the same type as the most recent opening bracket that is still unclosed, and closes it,
  • no closing bracket shows up while nothing is open,
  • no opening bracket is still unclosed when the string ends.
Example 1
Input: s = "{()[]}"
Output: true

Explanation: The () and [] pairs close inside the braces, and the braces close last.

Example 2
Input: s = "[(])"
Output: false

Explanation: The ] arrives while ( is the most recent unclosed bracket, so the types do not match.

Example 3
Input: s = "(()"
Output: false

Explanation: The second ( is closed, but the first one never is.

Constraints

  • s is between 1 and 10^4 characters long.
  • Only the characters ()[]{} appear in s.
💡 Hint 1

The most recently opened bracket must be the first one closed. Which data structure is last-in, first-out?

💡 Hint 2

At the end, anything still open means the string is invalid.

/**
 * @param {string} s
 * @return {boolean}
 */
function isValid(s) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc