BudiBadu Logo

Find Pivot Index

Array Easy 0 views
Like2

You are given an array of integers. The task is to find the pivot index, which is the position in the array where the sum of all elements to the left is equal to the sum of all elements to the right. If multiple pivot indexes exist, return the leftmost one. If no such index exists, return -1.

Think of the array as a balanced scale, where the pivot is the point that keeps both sides even. Each number on the left adds weight to one side, and each number on the right adds weight to the other. Your job is to find the position that keeps the balance perfectly. For example, if the total weight on both sides is the same, you have found the equilibrium point of the array.

This concept appears frequently in statistical analysis, balancing algorithms, and problems involving cumulative sums. The pivot helps to understand how data is distributed within a range. You must carefully track partial sums while traversing the array to detect balance efficiently.

Example 1:

Input: nums = [1,7,3,6,5,6]
Output: 3

Example 2:

Input: nums = [1,2,3]
Output: -1

Example 3:

Input: nums = [2,1,-1]
Output: 0

Algorithm Flow

Recommendation Algorithm Flow for Find Pivot Index - Budibadu
Recommendation Algorithm Flow for Find Pivot Index - Budibadu

Best Answers

java
import java.util.*;
class Solution {
    public int find_pivot_index(Object input) {
        int[] nums = (int[]) input;
        int total = 0;
        for (int x : nums) total += x;
        int left = 0;
        for (int i = 0; i < nums.length; i++) {
            if (left == total - left - nums[i]) return i;
            left += nums[i];
        }
        return -1;
    }
}