#2532

Time to Cross a Bridge

Hard
ArrayHeap (Priority Queue)SimulationPriority QueueSimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log k)
Space
O(1)
O(k)
💡

Intuition

Time O(n log k)Space O(k)

The optimal solution uses a priority queue to efficiently manage worker availability and prioritize the least efficient workers. This reduces the time complexity significantly by avoiding unnecessary checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a priority queue to manage workers based on their efficiency.
  2. 2Step 2: While there are boxes to move, dispatch the least efficient worker available to pick up a box.
  3. 3Step 3: Update the total time based on the worker's actions and repeat until all boxes are moved.
solution.py15 lines
1# Full working Python code
2import heapq
3
4def timeToCrossBridge(n, k, time):
5    pq = []
6    for i in range(k):
7        heapq.heappush(pq, (time[i][0] + time[i][2], i, time[i]))
8    total_time = 0
9    while n > 0:
10        _, worker_idx, worker_time = heapq.heappop(pq)
11        total_time += worker_time[0] + worker_time[1] + worker_time[2] + worker_time[3]
12        n -= 1
13        heapq.heappush(pq, (worker_time[0] + worker_time[2], worker_idx, worker_time))
14    return total_time
15

Complexity note: The complexity is O(n log k) because we are using a priority queue to manage k workers, and for each of the n boxes, we perform log k operations to manage the queue.

  • 1Using a priority queue allows us to efficiently manage worker availability and prioritize the least efficient workers.
  • 2Understanding the problem constraints helps in designing the simulation accurately.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.