Learn-dsa..in 30 days!



























CC-8 : Find the pivot point of the array.

Description:

Given an input integer array arr. The pivot point of the array is the element such that the sum of all array elements to the left of the pivot point is equal to sum of all elements to the right of the pivot point.

Test cases and expected outputs:

Input Parameters Expected outputs
arr={ 1,2,3,4,9,-3} Pivot point index is 3. Pivot point element is 4.
arr={4,5,4} Pivot point index is 1. Pivot point element is 5.
arr={1,3,5,7,3,5,1} Pivot point index is 3. Pivot point element is 7.
arr={1,-1,3} Pivot point index is 2. Pivot point element is 3. Note: sum of all index > arr.length-1 is assumed to be 0. Similarly sum of all index <0 can also be assumed to be 0.
arr={ 1,3,5,7,9,11,13} The array does not have a pivot point.

Pseudocode:

The java method should accept following input parameters: arr (int array).
Using a for loop find the sum of all elements and store it in variable sumElements.
Initialize int variable pivotPoint=0. We will find the value of pivotPoint in the next steps.
Initialize int variable sumLeft=0. We will use this variable to store sum of elements to the left of pivotPoint.
Initialize int variable sumRight= sumElements. We will use this variable to store sum of elements to the right of pivotPoint.
Iterate the array using for loop starting from 0 up to (arr.length-1) using pivotPoint as loop variable:
Reduce rightSum by arr[pivotPoint], this is because we iterate from 0 onwards, value of rightSum will reduce at each index.
If rightSum==leftSum, we have found the pivot point, return pivotPoint and arr[pivotPoint] and exit the loop.
Else Increment leftSum by arr[pivotPoint], this is because as we iterate from 0 onwards the value of leftSum will increase at each index.
If no pivotPoint is found by end of loop return null.

Code:

public int[] arrayFindPivotPoint(int[] arr) throws Exception{
	int sumElements=0;
	int[] retArr=new int[2];
	for (int idx=0; idx< arr.length; idx++) {
		sumElements+=arr[idx];
	}
	int pivotPoint=0;
	int leftSum=0;
	int rightSum=sumElements;
	for (pivotPoint=0; pivotPoint<arr.length;pivotPoint++) {
		rightSum-=arr[pivotPoint];
		if (rightSum==leftSum) {
			retArr[0]=pivotPoint; // pivot index
			retArr[1]=arr[pivotPoint]; // pivot element
				break;			
			}
		leftSum+=arr[pivotPoint];
	}
	if (pivotPoint>=arr.length) {
		return null; // no pivot point found			
	}
	return retArr;			
}

Click here to download and run code and test cases !