DEV Community

Cover image for 20. Valid Parentheses - JavaScript Solution - by Abu Saleh Faysal
Abu Saleh Faysal
Abu Saleh Faysal

Posted on

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

An array of parentheses are given. We need to find out if the array contains both opening and closing parentheses or not.

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.

/**
 * @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;
};

Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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

Top comments (0)