codejump
MediumPro challengePythonJavaScriptTypeScript

Async Semaphore

BackendAsyncConcurrency

Implement a semaphore limiting concurrent async ops to max.

solve(max, durations) starts one task per duration, all at once, through the
semaphore: task i waits durations[i] ms with setTimeout. Tasks get a slot
in index order — when one finishes, the oldest waiting task starts.

Return the task indices in the order they finish.

await solve(1, [30, 10, 20]) // [0, 1, 2] — one at a time
await solve(3, [30, 10, 20]) // [1, 2, 0] — all run together, shortest first
await solve(2, [60, 30, 10]) // [1, 2, 0] — task 2 waits for task 1's slot

Sample tests

Test #1max 1: tasks run one after another
Input: [1,[30,10,20]]
Output: [0,1,2]
Test #2All fit: shortest finishes first
Input: [3,[30,10,20]]
Output: [1,2,0]
Test #3Task 2 waits for the slot of task 1
Input: [2,[60,30,10]]
Output: [1,2,0]
Test #4Freed slots go to waiting tasks in index order
Input: [2,[80,10,30,20]]
Output: [1,2,3,0]
Test #5Single task
Input: [5,[20]]
Output: [0]