Open In App

Sum of Array Divisible by Size with Even and Odd Numbers at Odd and Even Index in Java

Given an array arr[] of size N, Convert the given array as even numbers in the array occurs at the odd index, odd numbers in the array occur at the even index, and whether the sum of the numbers in an array is divisible by the size of an array. If the array follows all the properties then an array is valid else it is invalid.

An array will be valid if it follows all the given three conditions:



  1. In the given array arr[], at every even index position, it must contain an odd number.
  2. In the given array arr[], at every odd index position, it must contain an even number.
  3. The sum of the given array arr[] must be divisible by the size of the given array.

Note: Array is 0 indexes based.

Examples:



Input : arr = {1, 2, 3, 4, 5, 6, 9, 10} 
Output: "VALID"
Explanation: 
 1.Sum of given array is 40, and size of array is 8
 2.At every even index position array containing odd number
 3.At every odd position index array containing even number

Input : arr = {11, 4, 9, 3, 13}
Output: "INVALID"
Explanation: 
 1.Sum of given array is 40, and size of array is 4
 2.At index 3 it containing an odd value which does not follow given condition
Hence it is invalid.

Approach:

Below is the implementation of the above approach:  




// Sum of Array Divisible by Size with Even
// and Odd Numbers at Odd and Even Index 
// in Java
public class Main {
    
    // check whether array is valid or not
    public static String validate(int[] arr)
    {
        // Finding size of given array
        int N = arr.length;
  
        // Store sum of given array
        int s = 0;
  
        // traverse the given array
        for (int i = 0; i < N; i++) {
            // store sum of elements
            s += arr[i];
  
            // if index is even and value is
            // odd, then continue
            if (i % 2 == 0 && arr[i] % 2 == 1)
                continue;
  
            // if index is odd and value is
            // even, then continue
            else if (i % 2 == 1 && arr[i] % 2 == 0)
                continue;
  
            // violeting given condition
            else
                return "INVALID";
        }
  
        // check last condition, sum is
        // divisible by size or not
  
        return s % N == 0 ? "VALID" : "INVALID";
    }
    // Driver Code
    public static void main(String[] args)
    {
  
        int[] arr = { 1, 2, 3, 4, 5, 6, 9, 10 };
        System.out.println(validate(arr));
  
        int[] barr = { 11, 4, 9, 3, 13 };
        System.out.println(validate(barr));
    }
}

Output
VALID
INVALID

Article Tags :