Alexander Obregon's Substack

Java LeetCode Solutions

LeetCode #20: Valid Parentheses

Alexander Obregon's avatar
Alexander Obregon
Aug 14, 2025
∙ Paid
Share
LeetCode Logo
Image Source

Valid Parentheses asks you to check whether a string containing only brackets is balanced. A balanced string means every opening bracket has a matching closing bracket and the pairs are arranged in the right order. The input can contain parentheses, square brackets, and curly braces, and the goal is to return true when the nesting rules hold for the entire string and false when they don’t.

A good way to think about solving it is to picture the process of tracking what’s still open as you scan from left to right. Each opener you see adds something to track, and each closer should match the most recent opener still waiting. If that match fails or a closer appears before any opener, the string is invalid. Reaching the end with nothing left to match means the string is valid. Approaching the problem this way makes it natural to use a stack, since it works in the same last-in, first-out order as the bracket nesting itself.

LeetCode: Valid Parentheses

Keep reading with a 7-day free trial

Subscribe to Alexander Obregon's Substack to keep reading this post and get 7 days of free access to the full post archives.

Already a paid subscriber? Sign in
© 2025 Alexander Obregon
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture