Find Pivot Index Visualizer & Step-by-Step Algorithm Solution

Find the leftmost pivot index where the sum of numbers strictly to the left equals the sum of numbers strictly to the right using prefix and suffix sums.

Category: arrays | Difficulty: Easy

Tags: Array, Prefix Sum

Find Pivot Index

Input Array (nums)
1
0
7
1
3
2
6
3
5
4
6
5
100%
state
n6
Initialization
1/20
Explanation

Call pivotIndex with array [1, 7, 3, 6, 5, 6]. Find leftmost index where left sum equals right sum.

Source Code
1function pivotIndex(nums: number[]): number {
2 const n = nums.length;
3
4 const prefix = Array(n + 1).fill(0);
5 const suffix = Array(n + 1).fill(0);
6
7 for (let i = 1; i <= n; i++) {
8 prefix[i] = prefix[i - 1] + nums[i - 1];
9 }
10
11 for (let i = n - 1; i >= 0; i--) {
12 suffix[i] = nums[i] + suffix[i + 1];
13 }
14
15 for (let i = 0; i < n; i++) {
16 if (prefix[i] === suffix[i + 1]) return i;
17 }
18
19 return -1;
20}