In: Other
Given an array of numbers, find the index of the smallest array element (the pivot), for which the sums of all elements to the left and to the right are equal. The array may not be reordered.
Example arr=[1,2,3,4,6]
the sum of the first three elements, 1+2+3=6. The value of the last element is 6.
Using zero based indexing, arr[3]=4 is the pivot between the two subarrays.
The index of the pivot is 3.
Function Description
Complete the function balancedSum in the editor below.
balanced Sum has the following
parameter(s):
int arr(n): an array of integers
Returns:
int: an integer representing the index of the pivot
Constraints
3≤n≤105
1≤ arr[i]≤ 2 * 104, where 0≤i
It is guaranteed that a solution always exists.
Approach used:
>>Maintain two pointers, leftptr, rightptr
>>Traverse array from both sides at once and calculate left_sum and right_sum to store array sum from right and left.
>>If left_sum < right_sum increment leftptr
>>If left_sum > right_sum decrement rightptr
>>When left_sum = right_sum and leftptr and rightptr have only one element in between which is pivot,
>>Return the pivot
-----------------------------------------------------------------------------------
I have included my code and screenshots in this answer. In case, there is any indentation issue due to editor, then please refer to code screenshots to avoid confusion.
----------------solution.java---------
import java.util.*;
import java.lang.String;
public class solution
{
public static void main(String[] args)
{
int arr1 [] ={1,2,3,4,6};
int pivot_index = balancedSum(arr1);
System.out.print("\nThe pivot index for arr1 is: " + pivot_index+"\n");
int arr2 [] ={10, 5, 5, 1, 9, 3, 1, 2 , 15};
pivot_index = balancedSum(arr2);
System.out.print("\nThe pivot index for arr2 is: " + pivot_index+"\n");
}
public static int balancedSum(int [] array) //returns pivot index for array
{
int leftptr = 0; //declare leftptr and rightptr
int rightptr = array.length-1;
int left_sum = array[leftptr]; //initialize left sum to first element
int right_sum = array[rightptr]; //initialize left sum to last element
while(rightptr - leftptr != 2) //do until there is one element between both pointers
{
if(left_sum <= right_sum){ //if left sum is less, increment leftptr and increase sum
leftptr++;
left_sum = left_sum + array[leftptr];
}
else{ //if right sum is less, decrement rightptr and decrease sum
rightptr--;
right_sum = right_sum + array[rightptr];
}
}
if(left_sum == right_sum) //if only one element exists in between and both sums are equal, then return pivot
return (leftptr+1);
else
return -1; //else return -1
}
}
----------------Screenshot solution.java---------