Given an array of integers
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
Return the leftmost pivot index. If no such index exists, return
Output: 3
Explanation: 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
Output: -1
Explanation: There is no index that satisfies the conditions in the problem statement.
Output: 0
Explanation: 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
Contents
Solution using two pointers
In this approach, what we are going to do is compute the total sum of array
Implementation details
-
We will create a function
usingTwoPointers that takes input argumentnums . -
In the first step, we are going to compute the total sum of elements and store it in a variable
total . -
Create two variable
leftSum to keep track left side elements sum andrightSum to hold right side elements sum. -
Then, loop through each element in the array and compute
leftSum andrightSum :-
To compute
leftSum keep adding current elements that we are looping through. -
To compute
rightSum , since we already knowtotal andleftSum , we can compute right elements sum as:rightSum = total - leftSum - nums[i]; // since we want strictly right side sum, we have to subtract current element
-
To compute
-
For any index
i , ifleftSum matches torightSum , then we have found answer at indexi , otherwise return-1 at the end.
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1).
Above implementations source code can be found at