#1116

Print Zero Even Odd

Medium
Concurrency
LeetCode ↗

Approaches

💡

Intuition

Time Space

The brute force approach involves using a simple loop to print zeros, even numbers, and odd numbers in the correct order. Each thread will wait for its turn to print, which can lead to inefficiencies.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a loop that runs 2n times.
  2. 2Step 2: In each iteration, print a zero followed by either an even or odd number based on the iteration count.
  3. 3Step 3: Use flags or conditions to ensure that the correct thread prints at the right time.
solution.py28 lines
1import threading
2
3class ZeroEvenOdd:
4    def __init__(self, n):
5        self.n = n
6        self.lock = threading.Lock()
7        self.count = 0
8
9    def zero(self, printNumber):
10        for _ in range(self.n):
11            self.lock.acquire()
12            printNumber(0)
13            self.count += 1
14            self.lock.release()
15
16    def even(self, printNumber):
17        for i in range(2, self.n * 2 + 1, 2):
18            while self.count % 2 != 1:
19                pass
20            printNumber(i)
21            self.count += 1
22
23    def odd(self, printNumber):
24        for i in range(1, self.n * 2, 2):
25            while self.count % 2 != 0:
26                pass
27            printNumber(i)
28            self.count += 1

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.