20. Valid Parentheses — JavaScript Solution — by Abu Saleh Faysal
An array of parentheses are given. We need to determine if the array contains both opening and closing parentheses.
Steps:
- Declare a variable called “stack” and store an empty array.
- Iterate a for loop over the given array and store the array elements inside a variable called “char”.
- 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.
- If the individual element is not an opening parentheses, take the last element from stack array and store it inside a variable named “topElement”.
- If “topElement” is not equal to “char”, return false.
- 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