Code Logo

Find Pivot Index

Published atDate not available
Easy 0 views
Like0

You can think of this as a small game with a very specific goal. In Find Pivot Index, you are trying to work toward the right number by following one clear idea.

This one is about building the best total or working out a final amount. You may need to choose which values should be included and which ones should be skipped. Sometimes the biggest number is not the smartest first choice if it hurts the rest of the plan. The goal is to finish with the best overall total, not just one good moment.

For example, if the input is nums = [1,7,3,6,5,6], the answer is 3. Example with input: nums = [1,7,3,6,5,6] Another example is nums = [1,2,3], which gives -1. Example with input: nums = [1,2,3]

This is a friendly practice problem, but it still rewards careful reading. The key is thinking about the whole plan, not only one choice at a time.

Example Input & Output

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

Example with input: nums = [1,7,3,6,5,6]

Example 2
Input
nums = [1,2,3]
Output
-1
Explanation

Example with input: nums = [1,2,3]

Example 3
Input
nums = [2,1,-1]
Output
0
Explanation

Example with input: nums = [2,1,-1]

Algorithm Flow

Recommendation Algorithm Flow for Find Pivot Index
Recommendation Algorithm Flow for Find Pivot Index

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