KatInterview

Leftmost Busiest Slot After Range Increments

Arrays & HashingAuto-graded · 25 test cases
MediumAuto-gradedArrays & Hashingdifference-arrayprefix-suminterval-updates

Last updated

Apply many inclusive range additions over a possibly huge array and return the index holding the largest total, breaking ties toward the smallest index.

A row of n slots, numbered 0 through n - 1, each start with a value of 0. You are given a list of m range updates. Each update is a triple [left, right, amount] meaning: add amount to every slot whose index lies in the inclusive range [left, right].

An amount may be positive, zero, or negative, and slots that no update touches keep a value of 0.

After all updates have been applied, report the index of the slot holding the largest final value. If several slots tie for the largest value, report the smallest such index.

The parameters arrive in this order: the slot count n, then the list of updates in the order they were issued. Only the final state matters for the answer — the order of updates does not affect the result.

Example walkthrough: with n = 5 and updates [[1, 3, 2], [2, 4, 3]], the slot values end up as [0, 2, 5, 5, 3]. The largest value is 5, reached at indices 2 and 3, so the answer is 2.

Constraints

  • 1 <= n <= 10^6
  • The number of updates may be 0 or more, with m <= 10^5
  • 0 <= left <= right < n for every update
  • amount is any integer, possibly negative or zero
  • The answer is derived only from the final values; do not rely on any particular update order
  • A correct solution should run in time roughly proportional to n + m, not n * m
  • If no updates are given, every slot is 0 and the answer is 0

Examples

Example 1

Input: busiest_slot_index(5, [[1, 3, 2], [2, 4, 3]])

Output: 2

Example 2

Input: busiest_slot_index(5, [[1, 3, 2], [2, 4, 3]])

Output: 2

Example 3

Input: busiest_slot_index(4, [[0, 3, -2]])

Output: 0

Hints

Hint 1

Applying each update slot by slot is too slow because a single update can touch the whole row — look for a way to record only where each update begins and ends.

Hint 2

Store `+amount` at `left` and `-amount` just past `right`, then walk the row left to right accumulating a running total to recover each slot's real value.

Hint 3

Track the best value and its index as you accumulate; use a strict 'greater than' comparison so the first (smallest) index wins ties, and initialize from the first real value so all-negative data works.