# 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

1var pivotIndex = function (nums) {2 const n = nums.length3 let [leftSum, rightSum] = [0, 0]4 const leftSums = []5 const rightSums = []67 for (let i = 0; i < n; i++) {8 leftSum += nums[i - 1] || 09 leftSums.push(leftSum)10 }1112 for (let i = n - 1; i >= 0; i--) {13 rightSum += nums[i + 1] || 014 rightSums.push(rightSum)15 }16 rightSums.reverse()1718 let res = -11920 for (let i = 0; i < n; i++) {21 if (leftSums[i] === rightSums[i]) {22 res = i23 break24 }25 }2627 return res28}

## References

## Comments

Loading comments...

## Tags

leetcode

array

prefix sum

## Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

**Fact corner:** Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

**Still hesitate?** Read HoningJS author's guide on dealing with Toptal interview process.

## Next Post

LeetCode: Valid Parentheses

Classic stack problem

## Previous Post

LeetCode: Height Checker

Clone and sort