How do you find the equilibrium pivot index where left prefix sum equals right suffix sum in O(1) space?
Equilibrium Pivot Index in $O(1)$ Space: Total Sum vs. Running Left Sum
An equilibrium pivot index is an index i where the sum of all elements strictly to the left of i equals the sum of all elements strictly to the right of i:
$$\text{left_sum}(i) = \text{right_sum}(i)$$
Instead of storing full left and right prefix/suffix arrays ($O(n)$ space), compute total_sum once, then sweep left-to-right with a single left_sum variable. At index i:
$$\text{right_sum}(i) = \text{total_sum} - \text{left_sum} - \text{nums}[i]$$
When left_sum == total_sum - left_sum - nums[i] (equivalently 2 * left_sum + nums[i] == total_sum), index i is a valid pivot. Return the leftmost matching index (or -1 if none exists).
Boundary Cases & Why Subtraction Works
- Index
0as Pivot: Before the loop starts,left_sum = 0. Fori = 0,right_sum = total_sum - 0 - nums[0]. If the rest of the array sums to0,0 == 0and index0is returned. - Last Index
n - 1as Pivot: Onceleft_sumincludes everything up ton - 2, ati = n - 1we haveright_sum = total_sum - left_sum - nums[n - 1] = 0. Ifleft_sum == 0, indexn - 1is returned. - Negative Numbers & Zeroes: Unlike non-negative sliding-window tricks, prefix/suffix balance works for negative numbers and zeroes without monotonicity assumptions.
- Integer Overflow: Use 64-bit accumulators (
long long/int64_t) in C++ fortotal_sumandleft_sumso intermediate sums do not overflow 32-bit integers.
Quick Trace: nums = [1, 7, 3, 6, 5, 6]
total_sum = 28, startleft_sum = 0:i = 0(nums[0] = 1):right_sum = 28 - 0 - 1 = 27(0 != 27);left_sumbecomes1.i = 1(nums[1] = 7):right_sum = 28 - 1 - 7 = 20(1 != 20);left_sumbecomes8.i = 2(nums[2] = 3):right_sum = 28 - 8 - 3 = 17(8 != 17);left_sumbecomes11.i = 3(nums[3] = 6):right_sum = 28 - 11 - 6 = 11(11 == 11) $\implies$ Pivot index3.
Code Implementation
Python Solution
def pivot_index(nums: list[int]) -> int:
total_sum = sum(nums)
left_sum = 0
for i, val in enumerate(nums):
right_sum = total_sum - left_sum - val
if left_sum == right_sum:
return i
left_sum += val
return -1
C++ Solution
#include <vector>
#include <cstdint>
int pivotIndex(const std::vector<int>& nums) {
int64_t total_sum = 0;
for (int val : nums) {
total_sum += val;
}
int64_t left_sum = 0;
for (int i = 0; i < static_cast<int>(nums.size()); ++i) {
int64_t right_sum = total_sum - left_sum - nums[i];
if (left_sum == right_sum) {
return i;
}
left_sum += nums[i];
}
return -1;
}
Complexity
- Time Complexity: $O(n)$ — one pass to sum the array and one pass to test each index.
- Auxiliary Space: $O(1)$ — uses only scalar sum and index variables.
You must log in or register to comment.
