Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Easy Stack High frequency Solution Available Practice Mode

Valid Parentheses LeetCode Solution

Tags: #String #Stack

Approach Summary

Push open brackets. On close bracket, check if top of stack is the matching open bracket.

Practice Mode 3 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Stack Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Stack pattern.

Framework: Stack • Interview Prep: Tested at FAANG • Explore all Stack problems & invariants →

How to Recognize This Pattern

  • Bracket matching
  • Nested structure validation

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)

Tags

String Stack

Frequently Asked Questions

What is the optimal time and space complexity for Valid Parentheses?
The optimal solution for Valid Parentheses achieves O(n) runtime complexity and requires O(n) auxiliary space. Time complexity is O(n) because each character in s is pushed and popped from the stack at most once. Space complexity is O(n) in the worst case (e.g. all opening brackets "(((((").
How do I identify that Valid Parentheses requires the Stack pattern?
In technical interviews, look for key problem signals: Bracket matching; Nested structure validation. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Stack strategy.
What critical edge cases must be handled in Valid Parentheses?
Essential edge cases to verify include: Odd length string (cannot be valid, can exit early); Closing bracket appears first with empty stack (e.g. "]" or ")("; returns false); Unmatched trailing open bracket (e.g. "()("; stack is non-empty at end, returns false); Mismatched bracket types (e.g. "(]"; returns false). Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Valid Parentheses?
Valid Parentheses is a Easy-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Google, Amazon, Facebook, Bloomberg.
Buy me a coffee
Daily Practice
0/0