VOOZH about

URL: https://www.geeksforgeeks.org/dsa/finding-index-with-superior-even-to-odd-average/

⇱ Finding index with Superior Even-to-Odd Average - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Finding index with Superior Even-to-Odd Average

Last Updated : 7 Nov, 2023

Given an array a[] of size N which consists of both positive and negative integers, the task is to find the index of the array for which the average of all the even elements on its LHS is Greater than the average of all the odd elements on its RHS (Follow 0-based Indexing).

Note:

  • The First Index and Last Index Cannot be valid answers because the first index will not have any elements on its LHS as well as last index will not have any elements on its RHS.
  • If there are multiple indices satisfying the above condition then return the smallest valid index as an answer.
  • Else if there is no such index in the given array then return -1.

Examples:

Input: a[] = {4, 6, 1, 6, 5, 3}
Output: 1
Explanation: The average of even numbers in the array before index 1 is 4 (elements = {4}) and the average of odd numbers in array a[] after index 1 (elements = { 1, 3, 5} ) is 3. Here Floor Value Is Considered While calculating the average hence smallest valid index is 1.

Input: a[] = { 1,5,3,4,6}
Output: -1
Explanation: In the given array there is no such index that satisfies the above condition because

  • LHS Even average for every index in the given array is {0, 0, 0, 0, 4}
  • RHS Odd average for every index in the given array is {2, 3, 0, 0, 0}
  • There is no such index that satisfies the given condition.
  • Hence - 1 is the answer.


Approach: To solve the problem follow the below steps:

  • Create an Prefix Even Average array and Suffix Odd Average array of length N.
  • Iterate array a[] over loop from 0 to N-1 and use average variable to track the average of even numbers and assign PrefixEvenAverage[i]=average .
  • If current number is even then add and update the average , do it for all indices of array a[]
  • In a Similar Way iterate array a[] over loop from N-1 to 0 for calculating Suffix Odd Average array values.
  • Initialize a answer variable with -1 for storing the answer.
  • Then Check For Every index from 1 to N and if the index is satisfying the condition mentioned in question then store the index in answer variable and break the loop.
  • Return The Answer.

Below is the code to implement the above approach:


Output
1

Time Complexity: O(N), where N is the length of the array.
Auxiliary Space: O(N), where N is the length of the array.

Comment