Skip to content
BytePatterns

Start Times Behind a Semaphore

MediumConcurrency#min-heap#event-simulation~20m

Problem

A download service lets at most permits jobs run at once, guarded by a counting semaphore. Jobs arrive as (arrive, duration) pairs, sorted by arrival time, and the semaphore is fair: blocked jobs acquire a permit in the order they arrived. A permit released at time t can be used by a job starting at time t. Return the time at which each job starts running. There are up to 100,000 jobs.

Examples

Input:  permits = 2, jobs = [(0, 5), (1, 3), (2, 4), (3, 1)]
Output: [0, 1, 4, 5]
Why:    the third job waits for the permit freed at 4, the fourth for the one freed at 5
Input:  permits = 1, jobs = [(0, 2), (0, 2), (10, 1)]
Output: [0, 2, 10]
Why:    the last job arrives after everything has finished, so it starts at once
Input:  permits = 3, jobs = [(0, 7), (0, 7)]
Output: [0, 0]
Why:    edge case, fewer jobs than permits means nobody ever waits

Hints

0 / 3

Stuck on the idea rather than the code? Semaphores covers it.