Leetcode #1116: Print Zero Even Odd
In this guide, we solve Leetcode #1116 Print Zero Even Odd in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You have a function printNumber that can be called with an integer parameter and prints it to the console. For example, calling printNumber(7) prints 7 to the console.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Concurrency
Intuition
The constraints allow a direct scan that keeps only the essential state.
By translating the requirements into a clean loop, the logic stays easy to reason about.
Approach
Iterate through the data once, updating the state needed to compute the answer.
Return the final state after the traversal is complete.
Steps:
- Parse the input.
- Iterate and update state.
- Return the computed answer.
Example
Input: n = 2
Output: "0102"
Explanation: There are three threads being fired asynchronously.
One of them calls zero(), the other calls even(), and the last one calls odd().
"0102" is the correct output.
Python Solution
from threading import Semaphore
class ZeroEvenOdd:
def __init__(self, n):
self.n = n
self.z = Semaphore(1)
self.e = Semaphore(0)
self.o = Semaphore(0)
# printNumber(x) outputs "x", where x is an integer.
def zero(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(self.n):
self.z.acquire()
printNumber(0)
if i % 2 == 0:
self.o.release()
else:
self.e.release()
def even(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(2, self.n + 1, 2):
self.e.acquire()
printNumber(i)
self.z.release()
def odd(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(1, self.n + 1, 2):
self.o.acquire()
printNumber(i)
self.z.release()
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.