In this article we are going to discuss a problem from arrays; this is one of the most commonly asked interview question of today.
 

Find index in an integer array that divides the sum of elements both side equally.

e.g. if { 1, 2, 3, 5, 4, 2 } is an array,3 is the index that divides both side of elements some equally. In this case 1+2+3 is equal to 4+2 so index 3 have to find.

Here is a straight forward solution for the problem, We can reverse the index of array that divides equally using mathematical calculations as shown in example below:
package com.tbNext.byexample;

public class TBArrayDividingEqually {
	public static void main(String[] args) {
		int[] arr = { 1, 2, 3, 5, 4, 2 };
		TBArrayDividingEqually arrayDividingEqually = new TBArrayDividingEqually();
		System.out.println("Deviding Index: "
				+ arrayDividingEqually.middleElementIndex(arr));
	}

	private int middleElementIndex(int arr[]) {
		int mIndex = -1;
		int rightSum, leftSum = 0;
		int arrSum = arraySum(arr);
		for (int i = 1; i < arr.length; i++) {
			leftSum += arr[i - 1];
			rightSum = arrSum - (leftSum + arr[i]);
			if (leftSum == rightSum) {
				mIndex = i;
				break;
			}
		}

		return mIndex;
	}

	private int arraySum(int arr[]) {
		int sum = 0;
		for (int i : arr)
			sum += i;
		return sum;
	}
}


Output:

Deviding Index: 3


That's it, we have seen how to Find index in an integer array that divides the sum of elements both side equally. In upcoming articles of Java Algorithms and interview series we will see more about Java and Related programming problems and solutions.
  • By Techburps.com
  • May 9, 2015
  • Programming