Today we have to write a program for finding the balance index in a given array. This problem can be solved on O( n ) time.

Approach 1

  1. Loop Through the array and calculate the sum ,let’s assume sum is equal to arraySum.
  2. Now again again iterate over array elements
    1. Calculate the sum of element say it is leftsum
    2. calculate the difference between arraySum and current Element in arraySum
    3. if arraySum is equal to leftSum, then current array index is the balance index.
  3. Otherwise return –1, means balance index is not present in the array.

Code:

        public static int BalanceIndex(int[] input)
        {
            int arraySum = 0;
            int leftSum = 0;
            int balnaceIndex = -1;
            //Calculate the sum of all elements
            for (int i = 0; i < input.Length; i++)
            {
                arraySum = arraySum + input[i];
            }

            Console.WriteLine("Sum of Array Elements : " + arraySum);

            for (int i = 0; i < input.Length; i++)
            {
                leftSum = leftSum + input[i];
                arraySum = arraySum - input[i];
                if (arraySum == leftSum)
                {
                    balnaceIndex = i;
                    return balnaceIndex;
                }
            }

            if (leftSum != arraySum)
            {
                return -1;
            }
            return balnaceIndex;
        }

Test Case

private static void BalanceIndexTest()

{

    int[] arr = new int[] { -7, 1, 5, 2, -4, 3, 0,8 };

    Console.WriteLine("Balance index for " + string.Join(",", arr) + " is : " + ArrayProblems.BalanceIndex(arr));

    int[] arr1 = new int[] { 1, 3, 4, 6, 7, 2, 5, 9, 1, 11, 9, 6, 5, 8, 9, 1 };

    Console.WriteLine("Balance index for " + string.Join(",", arr1) + " is : " + ArrayProblems.BalanceIndex(arr1));

    int[] arr2 = new int[] { -7, 1, 5, 2, -4, 3, 0};

    Console.WriteLine("Balance index for " + string.Join(",", arr2) + " is : " + ArrayProblems.BalanceIndex(arr2));


    int[] arr3 = new int[] { -7 };

    Console.WriteLine("Balance index for " + string.Join(",", arr3) + " is : " + ArrayProblems.BalanceIndex(arr));


}

Output

Sum of Array Elements : 8

Balance index for -7,1,5,2,-4,3,0,8 is : –1

Sum of Array Elements : 87

Balance index for 1,3,4,6,7,2,5,9,1,11,9,6,5,8,9,1 is : –1

Sum of Array Elements : 0

Balance index for -7,1,5,2,-4,3,0 is : 5

Sum of Array Elements : -7

Balance index for -7 is : -1