“Valid Parentheses” Cheat Sheet javascript solution

Fadi Tillman
2 min readJul 14, 2021

--

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.
  2. Open brackets must be closed in the correct order.”LeetCode

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)};

--

--

Fadi Tillman
Fadi Tillman

Written by Fadi Tillman

Lifelong learner , Full Stack Software Engineer.

No responses yet