JavaScript Solutions, Competitive programming in JavaScript, MCQ in JS

Saturday, 17 December 2022

Solution to LeetCode Problem 724. Find Pivot Index in JavaScript

 A Solution to LeetCode Problem 724. Find Pivot Index in JavaScript

Welcome to a solution for the LeetCode problem "Find Pivot Index"!

In this problem, we are given an array of integers and asked to find the index of the pivot element. 

The pivot element is defined as the element that separates the array into two equal sums on either side of the element. If no such element exists, we should return -1.

Problem Statement: 

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 1:

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

Example 2:

Input: nums = [1,2,3]
Output: -1
There is no index that satisfies the conditions in the problem statement.

Example 3:

Input: nums = [2,1,-1]
Output: 0
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0



  • 1 <= nums.length <= 104
  • -1000 <= nums[i] <= 1000


One approach to solving this problem is to iterate through the array and keep track of the running sum of elements to the left and right of the current element. 

Then, we can check at each iteration if the left sum is equal to the right sum. If it is, we have found the pivot element and can return the index. If we reach the end of the array and have not found a pivot element, we can return -1.

Here is some example code in JavaScript that demonstrates this approach:

function pivotIndex(nums) {
let leftSum = 0;
let rightSum = 0;
// Calculate the initial right sum
for (let i = 1; i < nums.length; i++) {
rightSum += nums[i];
for (let i = 0; i < nums.length; i++) {
// Check if the left sum is equal to the right sum
if (leftSum === rightSum) {
return i;
// Update the left and right sums
leftSum += nums[i];
if (i < nums.length - 1) {
rightSum -= nums[i+1];
// Return -1 if no pivot element was found
return -1;

This code has a time complexity of O(n) and a space complexity of O(1), as it only uses a constant amount of extra space to store the left and right sums.

I hope this helps as a starting point for solving the "Find Pivot Index" problem on LeetCode! Let me know if you have any questions or need further clarification.

No comments:

Post a Comment