Typorithm · easy

Valid Parentheses

valid-parenthesesstacks-queuesstackmatchinglifo
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Valid Parentheses

0%

Stacks & Queues

Push openers on a stack; each closer must match the most recent opener, and the stack must end empty.

Brackets nest, so the last opened must be the first closed — classic LIFO.

A stack holds open brackets; each closer pops and checks against its required opener.

A mismatch or a leftover opener at the end means the string is invalid.

01

Push openers, pop on closers.

02

Top opener must match the closer.

03

End with an empty stack.

function isValid(s) {
  const stack = [];
  const pairs = { ")": "(", "]": "[", "}": "{" };

  for (const ch of s) {
    if (ch === "(" || ch === "[" || ch === "{") {
      stack.push(ch);
    } else if (stack.pop() !== pairs[ch]) {
      return false;
    }
  }

  return stack.length === 0;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Open-bracket stack

Push opens; the most recent must match the next close.

const stack = []

2. Close → open map

Map each closing bracket to its required opener.

const pairs = { ")": "(", "]": "[", "}": "{" }

3. Push opener

Remember every opening bracket on the stack.

stack.push(ch)

4. Match the close

The top opener must match the current closer.

stack.pop() !== pairs[ch]

5. Fully closed

An empty stack means every bracket was matched.

return stack.length === 0

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Valid Parentheses: Lesson & Practice · Typorithm | ApplyDjinn