#1114
Print in Order
EasyConcurrencySemaphoreCondition Variable
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
In the optimal solution, we can use a more structured approach with semaphores or condition variables to manage the order of execution without busy waiting. This allows threads to efficiently wait for the appropriate signal to proceed.
⚙️
Algorithm
4 steps- 1Step 1: Initialize three semaphores for first, second, and third with initial values set to control the order.
- 2Step 2: In the first() method, signal the second semaphore after printing.
- 3Step 3: In the second() method, wait on the first semaphore and signal the third semaphore after printing.
- 4Step 4: In the third() method, wait on the second semaphore and print.
solution.py19 lines
1import threading
2
3class Foo:
4 def __init__(self):
5 self.sema1 = threading.Semaphore(0)
6 self.sema2 = threading.Semaphore(0)
7
8 def first(self):
9 print('first')
10 self.sema1.release()
11
12 def second(self):
13 self.sema1.acquire()
14 print('second')
15 self.sema2.release()
16
17 def third(self):
18 self.sema2.acquire()
19 print('third')ℹ
Complexity note: The complexity is O(n) because each thread executes in a linear sequence without any nested waiting or checks.
- 1Understanding thread synchronization is crucial in concurrent programming.
- 2Using semaphores or condition variables can greatly simplify thread coordination.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.