Skip to content

Edvins Antonovs

Find pivot index code challenge

My approach to solving LeetCode’s Find pivot index code challenge.


Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.


1Input: nums = [1,7,3,6,5,6]
2Output: 3
4The pivot index is 3.
5Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
6Right sum = nums[4] + nums[5] = 5 + 6 = 11


We create an initial array (total) where we calculate the total sum of the given array's (nums) elements using the Array.reduce() method. Also, we create leftSum and assign it to 0.

Then we start for a loop where we iterate through the nums array. We calculate rightSum during each iteration by subtracting the current iteration value and leftSum from the total. If the sums of the left and right parts are equal, we find the pivot index and return it. Otherwise, we update leftSum with the current iteration value and continue iterating through the array.

If by the time we finish the iteration and haven't found the pivot index, we return -1 according to the problem description.

1var pivotIndex = function (nums) {
2 const total = nums.reduce((a, b) => a + b);
4 let leftSum = 0;
6 for (let i = 0; i < nums.length; i++) {
7 rightSum = total - nums[i] - leftSum;
9 if (leftSum === rightSum) {
10 return i;
11 }
13 leftSum += nums[i];
14 }
16 return -1;


© 2024 by Edvins Antonovs. All rights reserved.