Leetcode 1114: Print in Order

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

You are given a class with three methods: first(), second(), and third(). These methods are called concurrently by three threads. The goal is to ensure that second() is executed only after first() has been executed, and third() is executed only after second() has been executed. The execution of these methods is asynchronous, and you need to design a mechanism that guarantees the correct order of execution regardless of the operating system’s thread scheduling.
Problem
Approach
Steps
Complexity
Input: The input is an array of integers, where the integers represent the order in which the threads call the methods: 1 for `first()`, 2 for `second()`, and 3 for `third()`.
Example: Input: nums = [1, 3, 2]
Constraints:
• nums is a permutation of [1, 2, 3].
Output: The output is the concatenation of the strings printed by each method in the correct order. For example, if `first()`, `second()`, and `third()` are printed in the correct order, the output will be 'firstsecondthird'.
Example: Output: 'firstsecondthird'
Constraints:
• The methods should be executed in the correct order, even if the threads are scheduled asynchronously.
Goal: Ensure that `second()` is executed after `first()`, and `third()` is executed after `second()`.
Steps:
• Use a mechanism to control the order of method execution, such as using mutex locks or condition variables.
• Track the current method that should be executed and allow each thread to proceed only when it is their turn to execute the corresponding method.
Goal: The input array will always be a permutation of [1, 2, 3], ensuring that each method will be called exactly once.
Steps:
• 1 <= nums.length <= 3
• nums is a permutation of [1, 2, 3].
Assumptions:
• The methods `first()`, `second()`, and `third()` are executed by three different threads.
• Thread scheduling is unpredictable, and the order of execution is determined by the input array.
Input: Input: nums = [1, 3, 2]
Explanation: In this case, thread A calls `first()`, thread B calls `third()`, and thread C calls `second()`. The expected output is 'firstsecondthird', as `second()` should execute after `first()`, and `third()` should execute after `second()`.

Input: Input: nums = [2, 1, 3]
Explanation: In this case, thread A calls `second()`, thread B calls `first()`, and thread C calls `third()`. The expected output is 'firstsecondthird', as the order must be adjusted to maintain correct execution.

Link to LeetCode Lab


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