Valid Parentheses Visualizer & Step-by-Step Algorithm Solution

Determine if an input string containing '(', ')', '{', '}', '[' and ']' is valid using a LIFO stack.

Category: stack | Difficulty: Easy

Tags: Stack, String, Matching

Valid Parentheses

Push / Pop (Top)
(Empty Stack)
Brackets Stack (LIFO)
100%
state
s"()[]{}"
stack.length0
iN/A
charN/A
Initialization
1/24
Explanation

Start isValid(s = "()[]{}").

Source Code
1function isValid(s) {
2 const stack = [];
3 const map = { ')': '(', '}': '{', ']': '[' };
4 for (let i = 0; i < s.length; i++) {
5 const char = s[i];
6 if (char in map) {
7 const top = stack.length > 0 ? stack.pop() : '#';
8 if (top !== map[char]) {
9 return false;
10 }
11 } else {
12 stack.push(char);
13 }
14 }
15 return stack.length === 0;
16}