Parcel-delivery app~35 min4s · 256 MBtarget O((n + q) log n) time, O(n) spacesegment-tree
You work on a freight booking tool. A depot has up to 100,000 trucks in a fixed loading order, and each truck has some room left, in kilograms.
Parcel batches arrive one at a time. A batch is loaded at the first truck with enough room for the whole batch, at or after the position where the loader stands. If no truck fits, the batch waits. Your team lead asks which truck takes each batch, for up to 100,000 batches.
Write book_trucks(free, requests).
free[i] is the room left in truck i, in kilograms.[start, need]. It looks at the trucks start, start + 1, and so on, and takes the first one with free[i] ≥ need.need, and the answer for that request is its position.start onwards has enough room, nothing changes and the answer is -1.Input: free = [4, 2, 7, 1], requests = [[0, 3], [0, 3], [1, 2], [2, 6]]
Output: [0, 2, 1, -1]| Request | Room before | Truck chosen | Room after |
|---|---|---|---|
[0, 3] |
4, 2, 7, 1 | 0 | 1, 2, 7, 1 |
[0, 3] |
1, 2, 7, 1 | 2 | 1, 2, 4, 1 |
[1, 2] |
1, 2, 4, 1 | 1 | 1, 0, 4, 1 |
[2, 6] |
1, 0, 4, 1 | none (-1) | 1, 0, 4, 1 |
Input: free = [5], requests = [[0, 5], [0, 1]]
Output: [0, -1]The first request fills the only truck exactly. The second finds no room.
Input: free = [9, 1, 9], requests = [[1, 5], [0, 5]]
Output: [2, 0]The first request starts at truck 1, so it skips truck 0, which has room, and takes truck 2.
1 ≤ len(free) ≤ 100,0000 ≤ free[i] ≤ 1,000,000,0001 ≤ len(requests) ≤ 100,0000 ≤ start < len(free) and 1 ≤ need ≤ 1,000,000,000.Scanning from start to the first fit costs up to 100,000 steps, and 100,000 requests cost 10 billion steps. That is too slow. You need about log n steps for each request, which is about 17. A request changes one truck, so the structure must take changes as well as searches.