Find Pivot Index

ARRAY

Problem

Create a function that takes an array of integers nums and returns the leftmost pivot index.

The pivot index is the position where the sum of elements on the left is equal to the sum of elements on the right. If the pivot is at the edge, consider the sum on the opposite side as 0.

If no such index exists, return -1.

Examples

pivotIndex([1,8,4,0,2,7]) // 2 /* Why? The pivot index is 2. Left sum = nums[0] + nums[1] = 1 + 8 = 9 Right sum = nums[3] + nums[4] + nums[5] = 0 + 2 + 7 = 9 */ pivotIndex([4,2,1]) // -1 /* No index satisfies the condition. */ pivotIndex([3,3,-2,-1]) // 0 /* Why? The pivot index is 0. Left sum = 0 (as there are no elements to the left of index 0) Right sum = nums[1] + nums[2] + nums[3] = 3 + -2 + -1 = 0 */
Loading...