45. Valid Brackets
Difficulty: Easy · Topic: DSA for data engineers
Write is_balanced(text): return True if every bracket in text ((), [], {}) is closed by the matching kind, in the right order. Other characters are ignored, so it works on SQL or JSON snippets.
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
is_balanced("select sum(x) from t where y in (1, 2) and z = '[a]'")Expected: True
Hints
Hint 1
Push every opening bracket on a stack (a list).Hint 2
A closing bracket must match the bracket on top of the stack; pop it.Hint 3
At the end the stack must be empty.Learn the concepts
- Lists, dicts and sets: what each operation costs · 7 min read. Pick the container from the question, and why a set turns an hour-long loop into a second.
- Sliding windows, sweeps and binary search · 5 min read. O(n) windows, sort-then-sweep for intervals, and bisect for as-of lookups.
More Python problems
- Two Sum · Easy
- First Non-Repeating Character · Easy
- Group Anagrams · Medium
- Longest Substring Without Repeats · Medium
- Top K Frequent with a Heap · Medium
- Latest Event at or Before a Time · Medium
- Merge K Sorted Linked Lists · Hard
- Task Order with Cycle Detection · Hard