Java Program to Find middle index of array where both ends sum is equal

Java Program to Find middle index of array where both ends sum is equal thumbnail
26K
By Dhiraj Ray 01 January, 2018

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.java
package 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());
        }
    }
}

Explanation

Take two pointers, one starting from 0th index and another starting from array&aposs length-1 and start finding the sum from both ends.The point where these pointers crosses each other is the middle index or position of the array.Hence find the sum and conclude.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.