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.length
3 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] || 0
9 leftSums.push(leftSum)
10 }
11
12 for (let i = n - 1; i >= 0; i--) {
13 rightSum += nums[i + 1] || 0
14 rightSums.push(rightSum)
15 }
16 rightSums.reverse()
17
18 let res = -1
19
20 for (let i = 0; i < n; i++) {
21 if (leftSums[i] === rightSums[i]) {
22 res = i
23 break
24 }
25 }
26
27 return res
28}

References

Original problem

Comments

Loading comments...

Tags

leetcode

array

prefix sum

Next Post

LeetCode: Valid Parentheses

Classic stack problem

Previous Post

HoningJS

Search Posts