Problem · Concurrency
Ordered Odd-Even Thread Output
Learn this problemProblem statement
Coordinate two workers over the integers from 1 through n. The odd worker may append only odd values and the even worker may append only even values. The shared output must be exactly [1, 2, ..., n].
Return the shared output after both workers finish. Use synchronization so a worker waits until the next value has its parity; do not generate two independent lists and merge them afterward.
Function
orderedOddEvenOutput(n: int) → int[]Examples
Example 1
n = 6return = [1,2,3,4,5,6]The odd and even workers alternate while preserving increasing order.
Example 2
n = 1return = [1]Only the odd worker appends a value.
Constraints
0 <= n <= 100000- The returned array is empty when
n = 0.