Skip to content
CodeItRaw
Stacks & Queues

Lesson 2/4

With one kind of bracket a counter does instead of a stack: up on an opener, down on a closer. With two kinds counters are fooled: ([)] has one opener and one closer of each kind, the numbers agree, and the order is wrong. A stack remembers not only how many there are but in what order they were opened.

depth = 0
for ch in text:
depth += 1 if ch == "(" else -1
if depth < 0:
return False
return depth == 0
The one-kind version. Both checks are needed: the counter must never go negative on the way (no closer before its opener) and must end at zero. Code that only looks at the end calls ")(" balanced.

Remember too that a stack turns the order round: put in 1, 2, 3 and you take out 3, 2, 1. To reverse something, filling a stack and emptying it is enough; if you want to keep the order, a stack is the wrong tool.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Reverse the Words

    Code reading · Bug Hunt

  2. 02

    Balanced Brackets

    Code reading · Review the AI

  3. 03

    Balanced Brackets

    Code reading · Break the Code

If you would rather not wait for the order, every problem is open without locks: Problem list