- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 48 lines of Python from the credited upstream file 2532.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def findCrossingTime(self, n: int, k: int, time: list[list[int]]) -> int:3 ans = 04 5 leftBridgeQueue = [6 (-leftToRight - rightToLeft, -i) for i,7 (leftToRight, pickOld, rightToLeft, pickNew) in enumerate(time)]8 rightBridgeQueue = []9 10 leftWorkers = []11 rightWorkers = []12 13 heapq.heapify(leftBridgeQueue)14 15 while n > 0 or rightBridgeQueue or rightWorkers:16 17 while leftWorkers and leftWorkers[0][0] <= ans:18 i = heapq.heappop(leftWorkers)[1]19 leftWorkers.pop()20 heapq.heappush(leftBridgeQueue, (-time[i][0] - time[i][2], -i))21 22 while rightWorkers and rightWorkers[0][0] <= ans:23 i = heapq.heappop(rightWorkers)[1]24 heapq.heappush(rightBridgeQueue, (-time[i][0] - time[i][2], -i))25 if rightBridgeQueue:26 27 28 29 i = -heapq.heappop(rightBridgeQueue)[1]30 ans += time[i][2]31 heapq.heappush(leftWorkers, (ans + time[i][3], i))32 elif leftBridgeQueue and n > 0:33 34 35 36 37 38 i = -heapq.heappop(leftBridgeQueue)[1]39 ans += time[i][0]40 heapq.heappush(rightWorkers, (ans + time[i][1], i))41 n -= 142 else:43 44 ans = min(leftWorkers[0][0] if leftWorkers and n > 0 else math.inf,45 rightWorkers[0][0] if rightWorkers else math.inf)46 47 return ans48