Menu
CoddyTech

Find Pivot Index

EasyPrefix sumpython iconjava iconcpp iconc iconjs icon+10

You get an array of integers nums. A pivot index is an index where the sum of the values to its left equals the sum of the values to its right. The value at the pivot itself belongs to neither side, and a side with no values sums to 0.

Return the leftmost pivot index, or -1 if no index is a pivot.

Function

pivotIndex(nums: integer-array) → integer
numsinteger-array
the array of integers to balance
Returnsinteger
the leftmost pivot index, or -1 when there is none

Constraints

  • 1 ≤ nums.length ≤ 104
  • -1000 ≤ nums[i] ≤ 1000

Examples

Input
nums = [3, 1, 5, 2, 2]
Output
2
Explanation
At index 2 the left side is 3 + 1 = 4 and the right side is 2 + 2 = 4. Index 0 and index 1 do not balance (left 0 against 10, left 3 against 9), so 2 is the leftmost pivot.

lock icon+17 hidden tests on Submit

challenge icon

Follow-up

Can you find the leftmost pivot reading each value only once, without adding up the total first? What does that cost in memory?

Reset code
def pivotIndex(nums):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [3, 1, 5, 2, 2]

Expected

2