Leetcode 1116: Print Zero Even Odd

grid47
grid47
Exploring patterns and algorithms
Jul 18, 2024 9 min read

You are given an instance of the class ZeroEvenOdd, which contains three functions: zero, even, and odd. The same instance of ZeroEvenOdd is passed to three different threads. Thread A calls zero() to print zeros, thread B calls even() to print even numbers, and thread C calls odd() to print odd numbers. The goal is to output a sequence of numbers in the order: 0, 1, 2, 3, …, 2n, where n is the given number, and the length of the sequence is 2n. The threads should execute asynchronously, ensuring that the sequence is printed correctly.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer `n`, which represents the length of the series to be printed. The total number of elements in the output series will be `2n`.
Example: Input: n = 3
Constraints:
• 1 <= n <= 1000
Output: The output should be a string that represents the sequence starting with '0', followed by odd and even numbers alternating, up to `2n`.
Example: Output: '010203'
Constraints:
• The output must contain the numbers in the correct order, alternating between 0, odd, and even numbers, starting with 0.
Goal: The goal is to ensure that the threads execute in the correct order, printing the sequence: '0', odd, even, and so on until `2n`.
Steps:
• Use mutexes to control the execution order of the threads. Each thread should print its number in the sequence.
• Thread A prints 0, then thread C prints the first odd number, and thread B prints the first even number, alternating until the sequence is completed.
Goal: Ensure that the threads execute asynchronously and print the sequence in the correct order without missing any number.
Steps:
• The threads should alternate correctly between printing 0, odd, and even numbers.
• The sequence must be printed exactly in the correct order for `2n` numbers.
Assumptions:
• Threads will be executed asynchronously, and we need to control the execution order using synchronization mechanisms.
Input: Input: n = 1
Explanation: In this case, the output sequence is '010', where thread A prints 0, thread C prints the first odd number 1, and thread B prints the first even number 2.

Input: Input: n = 2
Explanation: The output should be '0102', as thread A prints 0, thread C prints the first odd number 1, and thread B prints the second even number 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus