Find the only repeating element in a sorted array of size n using C++

C++Server Side ProgrammingProgramming

In this problem, we are given an 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 repeating element in a sorted array of size n.

Let’s take an example to understand the problem,

Input

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

Output

5

Solution Approach

A simple approach to solve the problem is by using linear search and checking if arr[i] and arr[i+1] have the same value. In this case, return arr[i] which is the value repeated.

Example 1

Program to illustrate the working of our solution

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

Output

The repeating value in the array is 4

Another approach to solve the problem is by using a binary search algorithm to find the element that occurred twice at mid index. If the middle index value repeats itself then print it. If it is not at index position, traverse right subarray otherwise traverse left subarray.

Example 2

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
int findRepeatingValueArr(int arr[], int s, int e){
   if (s > e)
      return -1;
   int mid = (s + e) / 2;
   if (arr[mid] != mid + 1){
      if (mid > 0 && arr[mid]==arr[mid-1])
         return arr[mid];
         return arr[findRepeatingValueArr(arr, s, mid-1)];
   }
   return arr[findRepeatingValueArr(arr, mid+1, e)];
}
int main(){
   int arr[] = {1, 2, 3, 4, 5, 6, 6, 7, 8, 9};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The repeating value in the array is "<<findRepeatingValueArr(arr, 0, n-1);;
   return 0;
}

Output

The repeating value in the array is 6
raja
Updated on 11-Feb-2022 11:50:52

Advertisements