Print Zero Even Odd — LeetCode 1116 Python Solution

MediumConcurrency
Problem
#1116
Reading time
5 min

The problem

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.

Example

Input
n = 2
Output
"0102"
Explanation
There are three threads being fired asynchronously.

Python solution

Python
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

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1116. Print Zero Even Odd?
LeetCode 1116. Print Zero Even Odd is rated Medium on LeetCode.
What is the time complexity of LeetCode 1116. Print Zero Even Odd?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1116. Print Zero Even Odd?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1116. Print Zero Even Odd cover?
LeetCode 1116. Print Zero Even Odd is tagged Concurrency on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview