# Find pivot index code challenge

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

### Problem

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`.

### Example

`.css-l84w3r{background-color:rgba(107,70,193,0.2);border:none;color:var(--theme-ui-colors-gray-2,#edf2f7);cursor:pointer;font-size:14px;font-family:"IBM Plex Sans",-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";-webkit-letter-spacing:0.025rem;-moz-letter-spacing:0.025rem;-ms-letter-spacing:0.025rem;letter-spacing:0.025rem;-webkit-transition:default;transition:default;position:absolute;top:0;right:0;z-index:1;border-radius:0 0 0 0.25rem;padding:0.25rem 0.6rem;}@media screen and (min-width:640px){.css-l84w3r{font-size:14px;}}@media screen and (min-width:768px){.css-l84w3r{font-size:16px;}}.css-l84w3r[disabled]{cursor:not-allowed;}.css-l84w3r:not([disabled]):hover{background-color:var(--theme-ui-colors-primary,#6b46c1);color:var(--theme-ui-colors-white,#fff);}`1Input: nums = [1,7,3,6,5,6]2Output: 33Explanation:4The pivot index is 3.5Left sum = nums + nums + nums = 1 + 7 + 3 = 116Right sum = nums + nums = 5 + 6 = 11``

### Solution

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);3
4  let leftSum = 0;5
6  for (let i = 0; i < nums.length; i++) {7    rightSum = total - nums[i] - leftSum;8
9    if (leftSum === rightSum) {10      return i;11    }12
13    leftSum += nums[i];14  }15
16  return -1;17};``````