724. Find Pivot Index
Asked at 15Meta43Amazon37Bloomberg34Google34Apple30Microsoft30Coupang94Myntra73Expedia73Attentive67IBM59Agoda57Accenture44tcs36Goldman Sachs21
Problem
Return the leftmost index where the sum of the elements strictly to its left equals the sum of the elements strictly to its right (an empty side sums to 0), or −1 if there is none.
Example: [1,7,3,6,5,6] → 3 (1 + 7 + 3 = 5 + 6); [1,2,3] → -1
Constraints: n ≤ 10⁴.
With total known, the right sum at i is total − left − nums[i]. Scan once, maintaining left; return the first i where both sides match.
Complexity: O(n) time, O(1) space.
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
total, left = sum(nums), 0
for i, x in enumerate(nums):
if left == total - left - x:
return i
left += x
return -1
assert Solution().pivotIndex([1, 7, 3, 6, 5, 6]) == 3
assert Solution().pivotIndex([1, 2, 3]) == -1
assert Solution().pivotIndex([2, 1, -1]) == 0
assert Solution().pivotIndex([0]) == 0
assert Solution().pivotIndex([-1, -1, 0, 1, 1, 0]) == 5
class Solution {
public int pivotIndex(int[] nums) {
int total = 0, left = 0;
for (int x : nums) total += x;
for (int i = 0; i < nums.length; i++) {
if (left == total - left - nums[i]) return i;
left += nums[i];
}
return -1;
}
}
func pivotIndex(nums []int) int {
total, left := 0, 0
for _, x := range nums {
total += x
}
for i, x := range nums {
if left == total-left-x { // left sum equals right sum
return i
}
left += x
}
return -1
}