Find Pivot Index
viaLeetCode
Problem Given an integer array, return the leftmost index where the sum of elements strictly to the left equals the sum strictly to the right; -1 if none exists.
Input / Output
- Input: int array nums. Output: pivot index or -1.
Constraints
- n up to 10^4; values may be negative; O(n) time, O(1) space expected.
Example
- nums = [1,7,3,6,5,6] → 3 (left 1+7+3 = 11 = right 5+6).
- nums = [2,1,-1] → 0 (empty left sum 0 = right 1+(−1)).
Expected approach
- Compute total = Σ nums once; sweep with a running leftSum: at index i, right sum = total − leftSum − nums[i]; return i when equal, else add nums[i] to leftSum. O(n) time, O(1) space. Edge cases: pivot at either end (empty side sums to 0) and negative numbers making non-monotonic sums (why binary search doesn't apply).
asked …