Problem statement
Given a string s made only of the characters (, ), [, ], { and }, return true if the brackets are valid.
A string is valid when every opening bracket is closed by a bracket of the same type, brackets close in the correct order, and every closing bracket has a matching opening bracket before it.
Examples
- Input
s = "()[]{}"- Output
true
- Input
s = "{[]}"- Output
true
Why: Nested pairs close from the inside out.
- Input
s = "([)]"
- Output
false
Why: The ) arrives while [ is still the most recent open bracket.
- Input
s = "(("- Output
false
Why: Two brackets are never closed.
Constraints
- 1 ≤ s.length ≤ 10⁴
- s contains only the six bracket characters.
How to answer it out loud
What it tests: Stack reasoning, invariant clarity, and careful handling of malformed input.
- 1Clarify
Clarify the allowed characters and whether an empty string is valid.
- 2Implement
Push opening brackets and require each closing bracket to match the top of the stack.
- 3Verify
Test early closings, unmatched openings, mixed bracket types, and empty input; state O(n) time.
From brute force to the best solution
| Approach | Idea | Time | Space |
|---|---|---|---|
| Repeated deletion | Remove (), [] and {} pairs until nothing changes; valid if the string empties. | O(n²) | O(n) |
| StackBest | Push opening brackets; each closing bracket must match the top of the stack. | O(n) | O(n) |
The most recently opened bracket is always the one that must close next — exactly the last-in, first-out order a stack gives you.
Reference solution
Each version is self-contained and has been run against the examples and test cases on this page.
def is_valid(s: str) -> bool: pairs = {")": "(", "]": "[", "}": "{"} stack = [] for ch in s: if ch in pairs: # closing bracket if not stack or stack[-1] != pairs[ch]: return False stack.pop() else: # opening bracket stack.append(ch) return not stack # leftover openers mean invalid- Time
- O(n)
- Space
- O(n)
- Approach
- Stack
Edge cases to run before you say “done”
| Input | Expected | Why it matters |
|---|---|---|
| s = ")" | false | A closer on an empty stack — the classic crash. |
| s = "((" | false | Openers left over at the end. |
| s = "([)]" | false | Counts match but the order is wrong. |
Answer the main question first, then take these on one at a time:
- Can you report the first invalid position?
- How would streaming input change the solution?
- What if other characters are allowed?
Check your recording or written solution against this list:
- Popping an empty stack
- Checking only counts instead of order
- Forgetting leftover opening brackets
This guide combines general interview-practice patterns with the public hiring material below. The practice prompt and coaching are PiriPiri AI editorial content, not official Amazon questions or answers.
Official sources reviewed 20 September 2026.