“Valid Parentheses” Cheat Sheet javascript solution

The Valid Parentheses is in the easy category and is a good start for understanding more challenging algorithms using the stack and array as a data structure. I will focus on explaining a solution that works and not on the O time and space complexity.

Challenge:

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

An input string is valid if:

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

Note:

// String s// Determine if valid// Valid = same type brackets && open/closed in correct order// Empty string = true// Return boolean 

Example:

Input: s = “[]”Output: true

Explanation:

create a valid brackets object to compare to a stack that will store the string brackets and return true or false.

1.Create an object of valid brackets

let validBracket = {
‘(‘:’)’,
‘{‘:’}’,
‘[‘:’]’
}

2. Create an array to sort the stack

let stack =[];

3. Loop through the string s

for (let char of s ) {

4. Check if validBracket

if (validBracket[char]){

5. If valid push through the stack

stack.push(validBracket[char])

6. If the last character not equal to char it is false

if (stack.pop()!== char ) return false

Solution:

var isValid = function(s) {let validBracket = {‘(‘:’)’,‘{‘:’}’,‘[‘:’]’}let stack =[];for (let char of s ) {if (validBracket[char]){stack.push(validBracket[char])} else {if (stack.pop()!== char ) return false}}return (!stack.length)};

--

--

Lifelong learner , Full Stack Software Engineer.

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