Time to Cross a Bridge - Problem

Imagine managing a bridge logistics operation where k workers must transport n boxes from an old warehouse on the right side to a new warehouse on the left side. The challenge? Only one worker can cross the bridge at a time, and each worker has different efficiency levels for each task.

Given:

  • n boxes to transport
  • k workers available
  • A 2D array time[i] = [righti, picki, lefti, puti] where:
    • righti: minutes to cross bridge from left to right
    • picki: minutes to pick up a box from right warehouse
    • lefti: minutes to cross bridge from right to left
    • puti: minutes to put box in left warehouse

Worker Efficiency Ranking: Worker i is less efficient than worker j if lefti + righti > leftj + rightj, or if they're equal and i > j.

Bridge Rules:

  1. Only one worker uses the bridge at a time
  2. Priority goes to the least efficient worker ready to cross
  3. Workers carrying boxes (right→left) have priority over empty workers (left→right)
  4. Stop sending workers once enough have been dispatched for remaining boxes

Return the total time when the last box reaches the left warehouse.

Input & Output

example_1.py — Basic Case
$ Input: n = 1, k = 3, time = [[1,1,2,1],[1,1,3,1],[1,1,4,1]]
Output: 6
💡 Note: Worker 2 (least efficient with crossing time 1+4=5) goes right (1 min), picks box (1 min), returns left (4 min) for total 6 minutes. The box is then put in 1 more minute, but the crossing completion time is what matters.
example_2.py — Multiple Workers
$ Input: n = 3, k = 2, time = [[1,9,1,8],[10,10,10,10]]
Output: 50
💡 Note: Worker 1 is less efficient (20 vs 2 total crossing time). Both workers will need to make multiple trips. Worker 1 gets priority for bridge usage due to being less efficient.
example_3.py — Edge Case
$ Input: n = 5, k = 1, time = [[2,3,4,1]]
Output: 49
💡 Note: Single worker must make 5 trips: each trip takes 2+3+4+1=10 minutes, so 5*10-1=49 minutes total (last put operation happens after crossing is complete).

Time & Space Complexity

Time Complexity
⏱️
O(n log k)

Each of the n boxes requires O(log k) operations for heap management

n
2n
Linearithmic
Space Complexity
O(k)

Storage for priority queues containing worker information

n
2n
Linear Space

Constraints

  • 1 ≤ n, k ≤ 104
  • time.length == k
  • time[i].length == 4
  • 1 ≤ righti, picki, lefti, puti ≤ 103
  • Each worker has positive time for all tasks
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen