20. Find the Pivot Index

EasyArrayArray

Given an integer array nums, find the leftmost pivot index — the index where the sum of all numbers strictly to its left equals the sum of all numbers strictly to its right. Return -1 if no such index exists.

Input: An integer array nums.

Output: Integer — leftmost pivot index, or -1.

Examples

Example 1
Input: [1,7,3,6,5,6]
Output: 3
Explanation: Left of index 3: 1+7+3=11. Right of index 3: 5+6=11. Equal → return 3.
Example 2
Input: [1,2,3]
Output: -1
Explanation: No index satisfies left_sum == right_sum → return -1.
Example 3
Input: [2,1,-1]
Output: 0
Explanation: Left of 0: empty sum = 0. Right of 0: 1+(-1)=0. Equal → return 0.

Constraints

Asked by

IBMMetaAmazonBloombergGoogleMicrosoft
Solve this problem in the editor →