We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A hard concurrency problem, graded against 5 test cases (2 of them hidden).
Coordinating threads with locks, semaphores, and condition variables.
Reach for it when you see: Ordering guarantees between threads, bounded buffers, or classic synchronisation puzzles.
More Concurrencyproblems →```
class ZeroEvenOdd:
n: int
counter: int # last number printed by even/odd, starts at 0
zeroSem: Semaphore(1) # zero() may run when this is up
oddSem: Semaphore(0) # odd() may run when this is up
evenSem: Semaphore(0) # even() may run when this is up
zero():
for i in 1..n:
zeroSem.acquire()
print(0)
if i is odd: oddSem.release()
else: evenSem.release()
odd():
for each odd i in 1..n:
oddSem.acquire()
print(i)
zeroSem.release()
even():
for each even i in 1..n:
evenSem.acquire()
print(i)
zeroSem.release()
```
The two-semaphore handshake guarantees ordering: `zero` only runs when zeroSem is up, `odd`/`even` only when their gate is up, and each role releases the next role's gate.
Why this is paper-only here
Our sandbox executors strip threading / asyncio / signal-based scheduling for safety. The simulation faithfully walks the same state machine; the test cases would all pass with a correctly synchronised real implementation.
Time / Space: O(n) prints, O(1) extra state.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
These apply to the pattern as a whole, not just this problem.