Valid Balanced Brackets in Python | Stack | Python Interview Prep #14
Code & Test Automation
0:00 / 0:00
Valid Balanced Brackets in Python | Stack | Python Interview Prep #14
1 просмотр · 2 дн. назад
Code & Test Automation
16 подписчиков
1 просмотр · 2 дн. назад
Code & Test Automation | / @codetestautomation
Learn how to check balanced brackets in Python with a stack, in O(n) time! In this lesson we cover the problem and its contract (properly nested (), [] and {} pairs, reject any other character, empty text is valid), why the latest opener must close first, the matching dictionary, the code line by line, a dry run of "([])" with the stack drawn step by step, the real python3 output including lone closers, leftover openers and 10,000 nested brackets, two traps (counting instead of using a stack, and popping an empty list), the follow-up of ignoring non-bracket characters so it works on real code, and the complexity.
Episode 14 of 20 in Python Interview Prep, beginner to intermediate, standard library only (strings, two pointers, hash maps and sets, XOR, binary search, Kadane, sliding windows, intervals, stacks, recursion, linked lists and trees). Every solution is run with real python3: Python 3.13.5 (and checked on Python 3.10.22).
CHAPTERS
0:00 Introduction
0:43 The problem
1:59 Intuition
2:47 The plan
3:12 The code
3:55 Dry run
4:28 Run it
5:34 The traps
6:52 Follow-up
7:33 Complexity
7:56 Recap
8:23 Subscribe
THE SOLUTION (Python)
def valid_brackets(text):
matching = {')': '(', ']': '[', '}': '{'}
stack = []
for char in text:
if char in '([{':
stack.append(char)
elif char in matching:
if not stack or stack.pop() != matching[char]:
return False
else:
return False
return not stack
REAL OUTPUT (Python 3.13.5; identical on Python 3.10.22)
valid_brackets("{[()]}") =› True
valid_brackets("([)]") =› False
valid_brackets("([])") =› True
valid_brackets("") =› True
Complexity: Time O(n); auxiliary space O(n) in the worst case.
Practice tip: try the prompt for 10 to 15 minutes first, then type the code, run it with python3, trace an example and test an edge case out loud.
Next episode: #15 Find the next greater value on the right.
#Python #PythonInterview #CodingInterview #CodeAndTestAutomation
Subscribe to Code & Test Automation for more Python and coding interview prep: / @codetestautomation