Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Valid Parentheses Check

Validate nested brackets with a Python stack. Students push openers, match the latest one first, and reject early closers or openings left at the end.

AdvancedPhase 5 - Category 5: Advanced String LogicExample 13 of 14
valid-parentheses-check.py
1# Take string
2s = input("Enter string with parentheses: ")
3
4# Check balance
5stack = []
6valid = True
7for char in s:
8 if char in '([{':
9 stack.append(char)
10 elif char in ')]}':
11 if not stack:
12 valid = False
13 break
14 top = stack.pop()
15 if (char == ')' and top != '(') or (char == ']' and top != '[') or (char == '}' and top != '{'):
16 valid = False
17 break
18
19if stack:
20 valid = False
21
22print("Valid" if valid else "Invalid")

Output

Enter string with parentheses: ()[]{}
Valid

In this one

  • Use last-in-first-out matching
  • Reject mismatched closers
  • Check leftover openers

How it works

  1. 1

    Push opening brackets onto stack.

  2. 2

    For a closer, require and pop a matching latest opener.

  3. 3

    Reject any leftover stack entries at the end.

Walk through Valid Parentheses Check

Text: ([)]

  1. 1.Push (, then push [; the latest opener is [.
  2. 2.The next character ) pops [ but requires (.
  3. 3.The mismatch sets valid false and ends the scan.

Edge cases

Does ([)] pass?

Does ([)] pass?

No. Its nesting order is wrong.

What happens for an extra closing bracket?

What happens for an extra closing bracket?

An empty stack triggers invalid before pop.

What's going on

The stack stores unfinished opening brackets. A closing bracket must match the most recently stored opener, which is removed with pop.

This last-in-first-out rule enforces nesting, not just equal counts. ([)] fails because ) encounters [. At the end, any remaining opener makes the input invalid. Nonbracket characters are ignored. Empty input has no mismatches or leftovers and is accepted.

Does ([)] pass? No. Its nesting order is wrong.

What happens for an extra closing bracket? An empty stack triggers invalid before pop.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why use a stack?

Pick an answer to check it.

Question 2

Does ([)] pass?

Pick an answer to check it.

Questions people ask

Does ([)] pass?

No. Its nesting order is wrong.

What happens for an extra closing bracket?

An empty stack triggers invalid before pop.

Why use a stack?

The latest opener must close first.