Problem Source: LeetCode
Companies: Facebook, Amazon, Google, Expedia, Microsoft, SalesForce
Given an array of integers nums
, write a method that returns the “pivot” index of this array.
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1
. If there are multiple pivot indexes, you should return the left-most pivot index.
Example 1:
Input: [1,2,3,4,6]
Output: 3
Example 2:
Input: [5,6,7]
Output: -1
Note:
The length of nums will be in the range [0, 10000]
.
Each element nums[i]
will be an integer in the range [-1000, 1000]
.
Solution:
From the problem statement it is clear that we need to check for a pivot index for every element in an array. To make an efficient code we need a suitable approach before we start to write the code.
In this problem, we need to calculate sum the elements to the left of the current element taken and sum of the elements to the right of it and then check if they are equal or not.
To simplify the problem, we can just calculate sum of all the elements in an array beforehand and then apply our main solution. This will reduce our tasks and we just have to calaculate left sum and then evaluate it for the required answer.
Algorithm:
- Create variables
total
andleftSum
and initialize them with0
. - Calculate the sum of all elements of the given array and update
total
to this sum. - To find the pivot index, traverse through the array by iteration and check whether
leftSum = total - leftSum - nums[i]
. - If the above condition is true then return
i
that will be your pivot index. - Return
-1
otherwise.
Implementation:
Java:
class Solution { public int pivotIndex(int[] nums) { int total = 0, leftSum = 0; for (int x: nums) total += x; for (int i = 0; i < nums.length; ++i) { if (leftSum == total - leftSum - nums[i]) return i; leftSum += nums[i]; } return -1; } }
Python:
class Solution(object): def pivotIndex(self, nums): total = sum(nums) leftSum = 0 for i, x in enumerate(nums): if leftSum == (total - leftsum - x): return i leftSum += x return -1