Skip to content

Valid Parentheses

Check that every bracket in a string is closed by the right type, in the right order, using a stack.

EasyStacks
Solve on LeetCode

The problem

You get a string s made only of the six bracket characters (, ), [, ], { and }. Return true if the brackets are balanced: every closing bracket must match the type of the most recent bracket that is still open, and no bracket may be left open at the end. Return false otherwise.

Input s = "{[()()]}"

Output true

Every closer matches the latest opener that is still waiting, and nothing is left open at the end.

Input s = "[{]}"

Output false

When `]` arrives, the most recent open bracket is `{`, so the order is wrong even though each type is counted correctly.

Key constraint: Counting each bracket type is not enough: the order matters, so [{]} has matching counts and is still invalid.

How to spot the pattern

  • Each closing item must match the most recent opening item that is still unmatched.
  • Pairs nest inside each other, like function calls or HTML tags.
  • You can only check a closer against the opener that came last.

The idea

The bracket that has to close next is always the one that was opened most recently. That is exactly what a stack gives you: push every opening bracket, and when a closing bracket arrives, it must match the bracket on top. If it doesn't match, or the stack is empty, the string is invalid, and at the end the stack has to be empty too.

Brute force: Keep deleting adjacent pairs like (), [] and {} until none are left, which can take O(n^2) time.

Step by step

  1. 1Keep a map from each closing bracket to its opening partner, and an empty stack.
  2. 2For each opening bracket, push it onto the stack.
  3. 3For each closing bracket, return false if the stack is empty or its top is not the matching opener; otherwise pop the top.
  4. 4After the loop, return true only if the stack is empty.

See the pattern move

The stacks pattern on a small example. Step through it, or press play.

Code

class Solution:
    def isValid(self, s: str) -> bool:
        partner = {")": "(", "]": "[", "}": "{"}  # closer -> opener
        stack = []
        for ch in s:
            if ch in partner:
                if not stack or stack[-1] != partner[ch]:
                    return False
                stack.pop()
            else:
                stack.append(ch)
        return not stack  # anything left is still open

Complexity

Time

O(n)

Space

O(n)

Each character is pushed and popped at most once; the stack can hold n characters when every bracket is an opener.

Watch out for

  • Forgetting the final check: (( never fails inside the loop, but it leaves two brackets open.
  • Reading the top of an empty stack when the string starts with a closer, like )(.
  • Only counting brackets of each type, which wrongly accepts [{]}.

Follow-up questions

Can you do it with O(1) extra space?

Only when there is a single bracket type: keep a counter that goes up on ( and down on ), fail if it ever drops below 0, and check that it ends at 0. With three types you have to remember the order, so you need the stack.

How many brackets would you have to add to make a string of ( and ) valid?

Walk the string with a balance counter. Each time a ) would push it below 0, count one missing ( and keep the balance at 0; at the end, the leftover balance is the number of missing ). The answer is the sum of the two.

In Hinglish

Jo bracket sabse last mein khula, wahi sabse pehle band hona chahiye. Isliye opener stack mein daalo, aur closer aaye toh top se match karo.

Related problems