# LeetCode: Find Pivot Index Solution

2 prefix sums

## Approach

Create two prefix sums:

• One for accumulated sum from left to right
• One for accumulated sum from right to left

Might reverse right-to-left one to be easier in later comparision (avoid

i
versus
n - i - 1
)

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var pivotIndex = function (nums) {2  const n = nums.length3  let [leftSum, rightSum] = [0, 0]4  const leftSums = []5  const rightSums = []6
7  for (let i = 0; i < n; i++) {8    leftSum += nums[i - 1] || 09    leftSums.push(leftSum)10  }11
12  for (let i = n - 1; i >= 0; i--) {13    rightSum += nums[i + 1] || 014    rightSums.push(rightSum)15  }16  rightSums.reverse()17
18  let res = -119
20  for (let i = 0; i < n; i++) {21    if (leftSums[i] === rightSums[i]) {22      res = i23      break24    }25  }26
27  return res28}```

Original problem

leetcode

array

prefix sum

## Next Post

LeetCode: Valid Parentheses

Aug 10, 2021

Classic stack problem

## Previous Post

LeetCode: Height Checker

Aug 3, 2021

Clone and sort

Search Posts