Find out middle index where sum of both ends are equal

You are given an array of numbers. Find out the array index or position
where sum of numbers preceeding the index is equals to sum of numbers
succeeding the index.

package com.java2novice.algos;
 
public class FindMiddleIndex {
 
    public static int findMiddleIndex(int[] numbers) throws Exception {
 
        int endIndex = numbers.length - 1;
        int startIndex = 0;
        int sumLeft = 0;
        int sumRight = 0;
        while (true) {
            if (sumLeft > sumRight) {
                sumRight += numbers[endIndex--];
            } else {
                sumLeft += numbers[startIndex++];
            }
            if (startIndex > endIndex) {
                if (sumLeft == sumRight) {
                    break;
                } else {
                    throw new Exception(
                            "Please pass proper array to match the requirement");
                }
            }
        }
        return endIndex;
    }
 
    public static void main(String a[]) {
        int[] num = { 2, 4, 4, 5, 4, 1 };
        try {
            System.out.println("Starting from index 0, adding numbers till index "
                            + findMiddleIndex(num) + " and");
            System.out.println("adding rest of the numbers can be equal");
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}
Share

Recent Posts

How to reverse Singly Linked List?

[crayon-66379e082e53a395444270/] [crayon-66379e082e54b859645849/] Output: Adding: 3 Adding: 32 Adding: 54 Adding: 89 3 32 54 89…

5 years ago

Find out duplicate number between 1 to N numbers.

[crayon-66379e082e664969243459/]

5 years ago

Write a singleton class in Java

Singleton class means you can create only one object for the given class. You can…

5 years ago

Write a java program to reverse a string?

1) Using StringBuffer class In this method, we use reverse() method of StringBuffer class to reverse the…

5 years ago

Write a java program to remove all white spaces from a string.?

1) Using replaceAll() Method. In the first method, we use replaceAll() method of String class…

5 years ago

Singly linked list implementation

Singly Linked Lists are a type of data structure. It is a type of list.…

5 years ago