Find Pivot Index

Easy· running sum

Problem

Return the leftmost index where the sum of all elements strictly to its left equals the sum of all elements strictly to its right. If no such index exists, return -1. An empty side counts as 0.

Examples

Input: nums = [1,7,3,6,5,6]
Output: 3
Left of index 3: 1 + 7 + 3 = 11. Right of it: 5 + 6 = 11.
Input: nums = [1,2,3]
Output: -1

Constraints

  • • 1 <= nums.length <= 10^4
  • • -1000 <= nums[i] <= 1000

Hints & approach

Hint 1

If you know the total and the sum to the left of i, you can derive the right sum.

Hint 2

right = total - left - nums[i].

Approachtry the hints first

Compute the total sum once. Walk the array with a running left sum; at each index i, the right sum is total - left - nums[i]. Return the first i where the two are equal, then add nums[i] to the left sum before moving on. Return -1 if no index qualifies.

Time O(n) · Space O(1)

Output
Call your solution with a test case and Run. For the full judge, submit on LeetCode.