Missing even and odd elements from the given arrays in C++


Problem statement

Given two integer arrays even [] and odd [] which contains consecutive even and odd elements respectively with one element missing from each of the arrays. The task is to find the missing elements.

Example

If even[] = {10, 8, 6, 16, 12} and
odd[] = {3, 9, 13, 7, 11} then
missing number from even array is 14 and from odd array is 5.

Algorithm

  • Store the minimum and the maximum even elements from the even[] array in variables minEven and maxEven
  • Sum of first N even numbers is N * (N + 1). Calculate sum of even numbers from 2 to minEven say sum1 and sum of even numbers from 2 to maxEven say sum2
  • The required sum of the even array will be reqSum = sum2 – sum1 + minEven, subtracting the even[] array sum from this reqSum will give us the missing even number
  • Similarly, the missing odd number can also be found as we know that the sum of first N odd numbers is N2

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void findMissingNums(int even[], int sizeEven, int odd[], int sizeOdd) {
   int minEven = INT_MAX;
   int maxEven = INT_MIN;
   int minOdd = INT_MAX;
   int maxOdd = INT_MIN;
   int sumEvenArr = 0, sumOddArr = 0;
   for (int i = 0; i < sizeEven; i++) {
      minEven = min(minEven, even[i]);
      maxEven = max(maxEven, even[i]);
      sumEvenArr += even[i];
   }
   for (int i = 0; i < sizeOdd; i++) {
      minOdd = min(minOdd, odd[i]);
      maxOdd = max(maxOdd, odd[i]);
      sumOddArr += odd[i];
   }
   int totalTerms = 0, reqSum = 0;
   totalTerms = minEven / 2;
   int evenSumMin = totalTerms * (totalTerms + 1);
   totalTerms = maxEven / 2;
   int evenSumMax = totalTerms * (totalTerms + 1);
   reqSum = evenSumMax - evenSumMin + minEven;
   cout << "Missing even number = " << reqSum - sumEvenArr << "\n";
   totalTerms = (minOdd / 2) + 1;
   int oddSumMin = totalTerms * totalTerms;
   totalTerms = (maxOdd / 2) + 1;
   int oddSumMax = totalTerms * totalTerms;
   reqSum = oddSumMax - oddSumMin + minOdd;
   cout << "Missing odd number = " << reqSum - sumOddArr << "\n";
}
int main() {
   int even[] = {10, 8, 6, 16, 12};
   int sizeEven = sizeof(even) / sizeof(even[0]);
   int odd[] = {3, 9, 13, 7, 11};
   int sizeOdd = sizeof(odd) / sizeof(odd[0]);
   findMissingNums(even, sizeEven, odd, sizeOdd);
   return 0;
}

When you compile and execute above program. It generates following output −

Output

Missing even number = 14
Missing odd number = 5

Updated on: 20-Dec-2019

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements