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.
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.