Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
A worker with base time t finishes successive units at times t, 3t, 6t, and so on. All workers operate in parallel, so the answer is the time of the mountainHeight-th completion across these sorted event sequences. A min-heap merges them.
Approach
Put each worker's first completion in the heap as (completionTime, baseTime, nextMultiplier), initially (t, t, 2). Repeat once per unit of mountain height: remove the earliest completion, record its time, and schedule that worker's next completion by adding baseTime * nextMultiplier. Increase the multiplier for the following event.
The heap always contains the next unprocessed completion from every worker. Therefore each removal is the earliest remaining unit of work across all workers, including simultaneous completions. After the required number of removals, the last recorded time is exactly when enough units have been removed, and no earlier time can suffice.
class Solution:
def minNumberOfSeconds(self, mountainHeight: int, workerTimes: List[int]) -> int:
h = []
for x in workerTimes:
heapq.heappush(h, (x, x, 2))
# (acc, base, count)
for x in range(mountainHeight):
acc, base, count = heapq.heappop(h)
res = acc
heapq.heappush(h, (acc + base * count, base, count + 1))
return resComplexity analysis
Let w = workerTimes.length and H = mountainHeight. Time is O((w + H) log(w + 1)): initialization performs w separate heap insertions, followed by H pop/push pairs. Using log(w + 1) includes the O(H) single-worker case. Auxiliary space is O(w). Completion times, including the next event scheduled after the last required one, fit within JavaScript's exact integer range under the given bounds.
