Taro Logo

Find Pivot Index

#91 Most AskedEasy
Topics:
ArraysTwo PointersSliding Windows

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

Example 2:

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

Example 3:

Input: nums = [2,1,-1]
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

Constraints:

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

Note: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected return value if the array is empty or null?
  2. Can the input array contain negative numbers and zeros, or are we guaranteed only positive integers?
  3. If there are multiple valid pivot indices in the array, which one should we return?
  4. How should edge cases be handled, such as an array with only a single element?
  5. Are elements strictly to the left and right of the pivot index inclusive or exclusive of the pivot element itself?

Brute Force Solution

Approach

Imagine you are given a line of numbered boxes, and you want to find a special spot where the total value of all the boxes to the left equals the total value of all the boxes to the right. The brute force approach simply tests every single box one by one, checking if it is the magic balance point.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first box in the line.
  2. Add up the values of all the boxes sitting to the left of this box, realizing that nothing is there.
  3. Then, add up the values of all the boxes sitting to the right of this box, going all the way to the end.
  4. Compare the total sum on the left with the total sum on the right to see if they match.
  5. If they do match, you have found your answer and can stop.
  6. If they do not match, move on to the next box in line.
  7. Repeat this exact process of adding up the left side and the right side for every single box until you find a match or run out of boxes.

Code Implementation

def find_pivot_index(numbers):    # Test every single box one by one to see if it acts as the balance point    for current_index in range(len(numbers)):        left_summation = 0        right_summation = 0                # Calculate total value of all boxes sitting to the left of the current box        for left_index in range(current_index):            left_summation += numbers[left_index]                    # Calculate total value of all boxes sitting to the right of the current box        for right_index in range(current_index + 1, len(numbers)):            right_summation += numbers[right_index]                    # Compare left and right totals to check if we found the magic balance point        if left_summation == right_summation:            return current_index                return -1

Big(O) Analysis

Time Complexity
O(n²) – For each of the n boxes in the line, the algorithm iterates through all the remaining boxes to calculate the separate sums for both the left and right sides. For the first box it checks n-1 others, for the second n-2 others, and this pattern repeats for every single position. Summing these checks together results in approximately n * n/2 total operations. Dropping the constant factor gives a final Big O time complexity of O(n²).
Space Complexity
O(1) – The brute force approach described relies entirely on computing sums on the fly without gathering items into a pile or creating temporary lists. The algorithm only allocates a few primitive variables to keep track of loop indices and running totals, which do not scale with the input size N. Because the memory consumption remains constant regardless of how many boxes are in the line, the auxiliary space complexity is O(1).

Optimal Solution

Approach

Instead of recalculating sums from scratch for every single position, the optimal approach looks at the big picture first by finding the total combined weight of everything. Then, it walks across the items one by one, keeping a running tally of what has been passed to instantly figure out what remains on the other side.

Here's how the algorithm would work step-by-step:

  1. Add up all the items in the entire collection to find the grand total weight.
  2. Imagine standing at the very beginning of the line with a current running weight of zero.
  3. Look at the current item and check if the running weight of everything behind you matches the remaining weight of everything ahead of you.
  4. If those two amounts happen to match, you have found your special balancing point.
  5. If they do not match, take the item you just crossed, add its weight to your running tally, and step forward to the next position.
  6. Repeat this checking process as you move forward until you either find the balancing point or run out of items to check.

Code Implementation

def pivotIndex(nums):
    # Calculate the grand total weight to determine the total sum of all elements.
    total_weight = sum(nums)
    
    running_weight = 0
    
    for index, current_item in enumerate(nums):
        # Check if the weight behind matches the remaining weight ahead.
        if running_weight == total_weight - running_weight - current_item:
            return index
            
        # Add the current item weight to the running tally before moving forward.
        running_weight += current_item
        
    return -1

Big(O) Analysis

Time Complexity
O(n) – To find the pivot index, we first iterate through all n elements of the array to calculate the total sum. Next, we iterate through the array a second time to maintain a running left sum and dynamically compute the right sum for each position. Each of these sequential passes processes the n items exactly once. This leads to a total operation count proportional to 2 * n, which simplifies to O(n).
Space Complexity
O(1) – The algorithm only maintains a fixed number of scalar variables, such as the grand total weight and the running weight, regardless of the input size. It does not allocate any auxiliary arrays, hash maps, or recursive call stacks. As the input size N grows, the extra memory required remains constant. Therefore, the auxiliary space complexity is O(1).

Edge Cases

Empty or null input array
How to Handle:
Return negative one immediately since no valid pivot index can exist in a non-existent or empty sequence.
Single-element array
How to Handle:
Return index zero because the left sum and right sum are both zero, satisfying the pivot condition.
Pivot index located at the extreme left edge
How to Handle:
Initialize the left sum to zero to correctly represent the absence of elements strictly to the left.
Pivot index located at the extreme right edge
How to Handle:
Ensure the right sum naturally evaluates to zero when no elements remain to the right of the current index.
Array containing negative numbers and zeros
How to Handle:
Maintain accurate running sums by using standard arithmetic additions and subtractions that properly handle negative values.
Multiple valid pivot indices exist in the array
How to Handle:
Iterate strictly from left to right and return the very first index encountered to satisfy the leftmost requirement.
No valid pivot index exists in the array
How to Handle:
Complete the full traversal without finding a matching condition and return negative one as specified.
Very large arrays with extreme integer values
How to Handle:
Use standard linear prefix sum tracking to compute values efficiently in O(N) time without risking integer overflow if within language limits.
0/245 completed