Online store~25 min2s · 256 MBtarget O((n + q) log n) time, O(n) spacesegment-tree
You work on a grocery delivery app. The slots along one aisle each show the price of the product on that shelf, in whole units. Prices change during the day.
A picker asks: "Which shelf in this stretch of the aisle is the cheapest?" Slots are numbered from 0. When two slots have the same lowest price, the picker wants the one with the lower number. An aisle can have 100,000 slots.
Write cheapest_slots(prices, ops).
prices[i] is the price in slot i.ops is a list of operations in time order. Each is [kind, a, b].[0, a, b] changes the price in slot a to b.[1, a, b] asks for the cheapest slot among slots a to b, both included, with a ≤ b. The answer is the slot number, and on a tie the lowest number.Input: prices = [8, 3, 5, 3, 9], ops = [[1, 0, 4], [0, 1, 10], [1, 0, 4], [1, 2, 4], [0, 4, 1], [1, 3, 4]]
Output: [1, 3, 3, 4]Apply the operations in order. On a tie the lower slot number wins, so the first answer is slot 1, not slot 3.
| Operation | Prices afterwards | Answer |
|---|---|---|
| Cheapest of slots 0 to 4 | [8, 3, 5, 3, 9] | slot 1 at 3 |
| Slot 1 now costs 10 | [8, 10, 5, 3, 9] | none |
| Cheapest of slots 0 to 4 | [8, 10, 5, 3, 9] | slot 3 at 3 |
| Cheapest of slots 2 to 4 | [8, 10, 5, 3, 9] | slot 3 at 3 |
| Slot 4 now costs 1 | [8, 10, 5, 3, 1] | none |
| Cheapest of slots 3 to 4 | [8, 10, 5, 3, 1] | slot 4 at 1 |
The answers are the slot numbers in the last column: 1, 3, 3, 4.
Input: prices = [4, 4, 4], ops = [[1, 0, 2], [1, 1, 2]]
Output: [0, 1]All slots cost the same, so the lowest number in the range wins.
Input: prices = [9], ops = [[1, 0, 0], [0, 0, 2], [1, 0, 0]]
Output: [0, 0]One slot. Its number is the answer whatever its price.
1 ≤ len(prices) ≤ 100,0000 ≤ prices[i] ≤ 1,000,0001 ≤ len(ops) ≤ 100,0000 ≤ a < len(prices). A change has 0 ≤ b ≤ 1,000,000. A question has a ≤ b < len(prices).Scanning the range of each question reads up to 100,000 slots, so 100,000 questions can make 10 billion reads. That is too slow for a 2-second limit. A running minimum does not work either: after a price rises, the old minimum cannot be undone. You need a structure that keeps the minimum of many ranges and repairs only a few of them after one change.