Find Pivot Index

EasyArrays & Hashingprefix sum

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums, return the **pivot index** of the array. The pivot index is the index i such that the sum of all the numbers strictly to the **left** of i is equal to the sum of all the numbers strictly to the **right** of i. If the index i is at the very start of the array, the left sum is 0 because there are no elements before it. The same logic applies to the right sum when i is the last element. Return the **leftmost** valid pivot index. If no such index exists, return -1.

Examples

Input: nums = [1,7,3,6,5,6]
Output: 3
At index 3, the left sum is 1 + 7 + 3 = 11 and the right sum is 5 + 6 = 11. They match, so 3 is the pivot index.
Input: nums = [1,2,3]
Output: -1
There is no index where the left and right sums are equal, so the answer is -1.
Input: nums = [2,1,-1]
Output: 0
At index 0, the left sum is 0 (no elements to the left) and the right sum is 1 + (-1) = 0. They match, so 0 is the pivot index.

Constraints

  • 1 <= nums.length <= 10^4
  • -1000 <= nums[i] <= 1000
  • The returned index, if any, must be the leftmost valid pivot index.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More prefix sum problems