LeetCode

Valid Parentheses

EasyStack & StringsDay 6

Problem Statement

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if open brackets are closed by the same type of brackets in the correct order.

Examples (Test Cases & Output)

Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([])"
Output: true

Constraints

  • 1 <= s.length <= 10^4
  • s consists of parentheses only '()[]{}'.

Target Complexities

Optimal TimeO(N)
Optimal SpaceO(N)
Core Algorithmic Insight:

Pushing the expected closing bracket instead of the opening bracket allows a direct equality check stack.pop() !== ch, making the code cleaner and faster.

Active Mode:Optimal Solution
Time: O(N)•Space: O(N)
Loading VS Code Hack Editor...
How This Code Works:

Use a Stack (LIFO). Iterate over characters: when an opening bracket is seen, push its matching closing bracket onto the stack. When a closing bracket is seen, pop from the stack and compare. If it doesn't match or stack is empty, return false. Finally check stack.length === 0.