Description
In the java interview, you will be asked to find the middle index or position of a given array where sum of numbers preceding the index is equals to sum of numbers succeeding the index.There are two ways to solve this problem.One is to use 2 for loops - one starting from the last index to the middle index and another starting from start index to middle index. Another way to solve it by using while loop - the while loop should stop when the start index crosses the end index. Following is the program to achieve this using while loop.
FindMiddleIndex.javapackage com.devglan; public class FindMiddleIndex { public static int findMiddleIndex(int[] array) throws Exception { int endIndex = array.length - 1; int startIndex = 0; int leftSum = 0; int rightSum = 0; while (true) { if (leftSum > rightSum) { rightSum += array[endIndex--]; } else { leftSum += array[startIndex++]; } if (startIndex > endIndex) { if (leftSum == rightSum) { break; } else { throw new Exception( "No such combination found in the array."); } } } return endIndex; } public static void main(String[] args) { int[] array = {1,7,5,2,8,3 }; try { int index = findMiddleIndex(array); System.out.println("Sum preceding the index " + index + " is equal to sum succeeding the index " + index); } catch (Exception ex) { System.out.println(ex.getMessage()); } } }