20. Valid Parentheses — JavaScript Solution — by Abu Saleh Faysal

Abu Saleh Faysal
2 min readFeb 10, 2023

--

An array of parentheses are given. We need to determine if the array contains both opening and closing parentheses.

Steps:

  1. Declare a variable called “stack” and store an empty array.
  2. Iterate a for loop over the given array and store the array elements inside a variable called “char”.
  3. Using switch case, check the elements and in case the individual element is an opening parenthesis, push a closing parentheses in stack array which was declared earlier.
  4. If the individual element is not an opening parentheses, take the last element from stack array and store it inside a variable named “topElement”.
  5. If “topElement” is not equal to “char”, return false.
  6. After the completed iteration, check the length of “stack” array is zero, if it is zero, return true and if it is not zero, return false.
  • Runtime: 86 ms.
  • Memory: 42.8 MB.
COPY
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
let stack = [];

for(let i = 0; i < s.length; i++) {
let char = s[i];

switch(char) {
case "(": stack.push(")");
break;

case "{": stack.push("}");
break;

case "[": stack.push("]");
break;

default:
let topElement = stack.pop();
if(char !== topElement) {
return false;
}
}

}
return stack.length === 0;
};

👉 Support me: https://www.buymeacoffee.com/abusalehfaysal

👉 YouTube Channel: https://www.youtube.com/@thebacklogprogrammer

👉 PlayList Link: https://youtube.com/playlist?list=PLUnklBXn8NSefCpBaLe39mds6dQx-tDDD

👉 Connect with me (LinkedIn): https://www.linkedin.com/in/abusalehfaysal

👉 Follow our LinkedIn Page: https://www.linkedin.com/company/thebacklogprogrammer/

👉 Like our Facebook page: https://www.facebook.com/thebacklogprogrammer/

👉 Join our community (Facebook group): https://www.facebook.com/groups/5500588936676942/

👉 Follow me at: https://www.facebook.com/AbuSalehFaysal10

👉 Twitter: https://twitter.com/AbuSalehFaysal

👉 Abu Saleh Faysal’s Blog: https://abusalehfaysal.hashnode.dev/

👉 Hasnode: https://hashnode.com/@AbuSalehFaysal

👉 Dev Community: https://dev.to/abusalehfaysal

👉 freeCodeCamp: https://www.freecodecamp.org/abusalehfaysal

👉 Medium: https://abusalehfaysal.medium.com/

👉 GitHub: https://github.com/AbuSalehFaysal
👉 GitLab: https://gitlab.com/AbuSalehFaysal

--

--

Abu Saleh Faysal

Software Engineer at Onethread | Front-End Developer | Blockchain Enthusiast | JavaScript | TypeScript | React | Redux