Solving Leetcode 20: Valid Parentheses in JavaScript

The Problem:

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.

Open brackets must be closed in the correct order.

Example 1:

Example 2:

Example 3:

The first thing I’m going to do is create a stack that will contain the array of values.

Next, I will iterate through the string:

Now, we need to check that the character that we’re on is an open parenthesis, if it is, we’re going to push the closing parenthesis to the stack. If it isn’t, and is instead a different opening bracket, we will push that other bracket’s closing bracket to the stack.

Remember: We have three bracket types in total.

If you haven’t passed out yet, keep it together, we’re half-way through.

Now, if the character at i isn’t an open bracket, we’re going to pull a character from the stack and check if the last element in the array matches it. If it doesn’t, we’re going to return “false”.

From here, we will check to see if the stack still contains characters.

If it does, that means that the parenthesis (and other brackets) are not closed. So, we return false.

If the stack is empty, that means everything matched up and we return true.

✨✨✨And that’s it!

Tish⚡️🎧🌙

--

--

MHA grad & Software Engineer | Rails | React | JavaScript | CSS | HTML

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tish Faroul

MHA grad & Software Engineer | Rails | React | JavaScript | CSS | HTML