Find Pivot Index in Array | Array Problem

4 years ago Lalit Bhagtani 0

Problem Statement

Pivot index is defined as an index whose sum of the numbers to the left is equal to the sum of the numbers to the right.

You have given an array of integers. Write a program to return the pivot index of the given input array if no such index exists, then return -1. If there are multiple pivot indexes, then return the left-most pivot index.

Example 

Find Pivot Index in Array

Input :- [4, 7, 3, 6, 8, 6]
Output :- 3
Input :- [4, 1, 3, 2, 4, 6]
Output :- -1

Solution

This problem can be solved in following steps :-

  1. Traverse the given input array Nums to calculate the sum of all its elements, let’s say Sum.
  2. Again traverse the input array from start (index 0) to end (n-1, where n is the length of an array) and calculate the sum of its traversed elements, let’s say LeftSum. If at any index LeftSum is equal to Sum – LeftSum – Nums[i], then i is a pivot index.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		int result = main.pivotIndex(new int[] {4, 7, 3, 6, 8, 6});
		System.out.print(result);		
	}
	
	/* Solution */    
	public int pivotIndex(int[] nums) {
        
        int sum = 0;
        for(int value : nums){
            sum = sum + value;
        }
        
        int start = 0, index = 0;
        for(index=0; index<nums.length; index++){
            
            sum = sum - nums[index];
            if(start == sum){
                return index;
            }
            start = start + nums[index];
        }
        return -1;
    }
}

Result

3 

Similar Post

  1. Rotate Array
  2. Maximum Subarray
  3. Positions of Large Groups

That’s all for Find Pivot Index in Array in Java, If you liked it, please share your thoughts in a comments section and share it with others too.