Stack & Monotonic Stack · Easy

Valid Parentheses

O(N) · O(N)

Initialize Stack

Check if string "({[]})" contains valid matching brackets using a LIFO Stack.

Array Elements & Pointers
(
i=0
{
i=1
[
i=2
]
i=3
}
i=4
)
i=5
LIFO Stack Container
Stack is currently empty
Live Variables & Invariants
s:({[]})
stackSize:0
Step 1 / 8
13%
Solution Code
1
function isValid(s: string): boolean {
2
  const stack: string[] = [];
3
  const map: Record<string, string> = { ')': '(', '}': '{', ']': '[' };
4
  for (const char of s) {
5
    if (char in map) {
6
      if (stack.pop() !== map[char]) return false;
7
    } else stack.push(char);
8
  }
9
  return stack.length === 0;
10
}
LeetCode IDE Console

Test Cases

5 cases from Blind 75 & NeetCode 150

Ask for a hint whenever you get stuck.