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 sum 3 + 1 = 4 balances the right sum 2 + 2 = 4. Index 0 gives 0 against 10 and index 1 gives 3 against 9, so 2 is the leftmost pivot.
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 #1

Test #2

Test #3

Argument

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

Expected Output

2