Find the only repetitive element between 1 to n-1 using C++

C++Server Side ProgrammingProgramming

In this problem, we are given an unordered array arr[] of size N containing values from 1 to N-1 with one value occuring twice in the array. Our task is to find the only repetitive element between 1 to n-1.

Let’s take an example to understand the problem,

Input

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

Output

1

Solution Approach

A simple solution to the problem is traversing the array and for each value find whether the element exists somewhere else in the array. Return the value with double occurrence.

Example 1

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findRepValArr(int arr[], int n){
   for(int i = 0; i < n; i++)
   for(int j = i+1; j < n; j++)
   if(arr[i] == arr[j])
      return arr[i];
}
int main(){
   int arr[] = { 5, 3, 2, 6, 6, 1, 4 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The repetitive value in the array is "<<findRepValArr(arr, n);
   return 0;
}

Output

The repetitive value in the array is 6

Another approach to solve the problem is by using the fact that the repetitive value in the array is found by subtracting the sum of all integers from 1 to (N-1) from the array sum.

Sum of 1st N-1 natural number (Sn) = n*(n-1)/2

doubleVal = arrSum - (Sn)

Example 2

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findRepValArr(int arr[], int n){
   int arrSum = 0;
   for(int i = 0; i < n; i++)
      arrSum += arr[i];
   int sn = (((n)*(n-1))/2);
   return arrSum - sn;
}
int main(){
   int arr[] = { 5, 3, 2, 6, 6, 1, 4 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The repetitive value in the array is "<<findRepValArr(arr, n);
   return 0;
}

Output

The repetitive value in the array is 6
raja
Updated on 11-Feb-2022 12:00:18

Advertisements