Easy Problems

20. Valid Parentheses

What will be learned

  • Learn stack operations and their applications in balancing symbols.

Solutions

const map = {
   "(": ")",
   "{": "}",
   "[": "]"
}
 
function isValid(s: string): boolean {
   let stack = [];
   for(let i = 0; i < s.length; i++) {
       const c = s[i]
       if(c in map) {
           stack.push(c)
       } else {
           if(stack.length === 0) {
               return false;
           }
           let open = stack.pop();
           if(map[open] !== c) {
               return false;
           }
       }
   }
   return stack.length === 0;    
};

Video Solution

...this is such a common interview question, I think I've been asked this so many times, like in a phone interview and online...so definitely a good problem to understand

Last Update: 12:08 - 16 April 2024
String
Stack

On this page