Monitoring~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-724prefix-sums
A monitoring system records the requests per second of a service in a row of servers, one number for each server. The on-call engineer wants to know where the load balances.
A server is a pivot when the total load of the servers to its left equals the total load of the servers to its right. The load of the pivot itself is not counted on either side.
If several servers qualify, the engineer wants the leftmost one. A row can hold 100,000 servers.
Write pivot_index(loads).
loads[i] is the load of server i.i is a pivot when the total of loads[0..i - 1] equals the total of loads[i + 1..n - 1]. An empty side has total 0.Input: loads = [2, 1, 7, 9, 5, 1, 4]
Output: 3The total is 29. A place is a pivot when the left total equals 29 minus the left total minus the load of the place.
| Place | Load | Left total | Right total | Balanced |
|---|---|---|---|---|
| 0 | 2 | 0 | 27 | no |
| 1 | 1 | 2 | 26 | no |
| 2 | 7 | 3 | 19 | no |
| 3 | 9 | 10 | 10 | yes |
| 4 | 5 | 19 | 5 | no |
| 5 | 1 | 24 | 4 | no |
| 6 | 4 | 25 | 0 | no |
Input: loads = [2, 3, 5]
Output: -1No server has equal totals on both sides.
Input: loads = [0, 0, 0]
Output: 0Place 0 has an empty left side and a right side of 0. It is the leftmost pivot.
1 ≤ loads.length ≤ 100,000 (servers in the row)0 ≤ loads[i] ≤ 1,000,000 (requests per second)Adding up both sides for each of 100,000 places costs about 10^10 additions. That is too slow.
One pass with a running left total tests each place in O(1). Totals reach 10^11, so use 64-bit integers.