Find the repeating and the missing number using two equations in C++


In this problem, we are given an array arr[] of size N. It consists of integer values ranging from 1 to N. And one element x from the range is missing whereas one element y in the array occurs double. Our task is to find the repeating and the missing number using two equations.

Let’s take an example to understand the problem,

Input

arr[] = {1, 2 , 3, 3}

Output

missing = 4, double = 3

Solution Approach

A method to solve the problem is using two equations for the two values x and y. Then solve the equation to get the value for x and y.

Let’s see the equations and how to create them,

The sum of elements of the array consists of sum of first N natural number with one element extra and one missing.

arrSum = Sum(N) - x + y
y - x = arrSum - sum(N)

This is equation 1.

Now, let's take square sum. Similarly,

arrSumsq = sqSum(N) - x2 + y2
(y - x)*(y + x) = arrSumSq - sqSum(N)

Using equation 1,

x + y = (arrSumSq - sqSum(N)) / (arrSum - sum(N))

Add both equations we get

y = (arrSumSq - sqSum(N)) / (arrSum - sum(N)) + (arrSum - sum(N)) / 2

Then using the value of y, we will find x using

x = y - (arrSum - sum(N))

We have formula for

sum(N) = n*(n-1)/2
sqSum(N) = n*(n+1)*(2n + 1)/ 6

arrSum is sum of all elements of array 

arrSumSq is the sum of squares of all elements of the array.

Example

Program to illustrate the working of our solution,

#include <iostream>
using namespace std;
void findExtraAndMissingVal(int arr[], int n){
   int sumN = (n * (n + 1)) / 2;
   int sqSumN = (n * (n + 1) * (2 * n + 1)) / 6;
   int arrSum = 0, arrSqSum = 0, i;
   for (i = 0; i < n; i++) {
      arrSum += arr[i];
      arrSqSum += (arr[i]* arr[i]);
   }
   int y = (((arrSqSum - sqSumN) / (arrSum - sumN)) + sumN - arrSum) / 2;
   int x = arrSum - sumN + y;
   cout<<"The missing value from the array is "<<x;
   cout<<"\nThe value that occurs twice in the array is "<<y;
}
int main() {
   int arr[] = { 1, 2, 2, 3, 4 };
   int n = sizeof(arr)/sizeof(arr[0]);
   findExtraAndMissingVal(arr, n);
   return 0;
}

Output

The missing value from the array is 2
The value that occurs twice in the array is 5

Updated on: 11-Feb-2022

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements