Find an index where the sum of elements to the left equals the sum of elements to the right.
Pivot Index
gfgGiven an integer array nums, return the leftmost pivot index if it exists.
A pivot index is an index i such that the sum of all elements strictly to the left of i is equal to the sum of all elements strictly to the right of i.
If there are multiple valid pivot indices, return the smallest one. If no such index exists, return -1.
Input Format
- A single integer array
nums. - The array contains one or more integers.
Output Format
- Return the smallest index
isuch that the sum of elements on the left ofiequals the sum of elements on the right ofi. - If no pivot index exists, return
-1.
Constraints
1 <= nums.length- The array may contain positive, negative, and zero values.
- Use 64-bit arithmetic if needed to avoid overflow.
Example 1
Input
nums = [1,7,3,6,5,6]
Output
3
Explanation
The left sum of index 3 is 1 + 7 + 3 = 11, and the right sum is 5 + 6 = 11.
Example 2
Input
nums = [1,2,3]
Output
-1
Explanation
No index has equal sums on both sides.
Show 1 more example
Example 3
Input
nums = [2,1,-1]
Output
0
Explanation
The left side of index 0 is empty, so its sum is 0. The right side is 1 + (-1) = 0.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.