Count of only repeated element in a sorted array of consecutive elements in C++

C++Server Side ProgrammingProgramming

We are given an array of consecutive numbers of length n. The array has only one number which is repeated more than once. The goal is to get the number of times that element is repeated in the array. Or we can say find the length of a repeated element in the array.

We will traverse the array from i=0 to i<n. If any arr[i]==arr[i+1] increment count. At last increment count by 1 for last element. Count will have length of repeated element.

Let’s understand with examples.

Input − arr[]= { 0,1,2,3,3,3 }, N=6

Output − Count of only repeated element − 3

Explanation − 3 is repeated thrice here.

Input − arr[]= { 1,2,3,4,4,4,4,4,5,6 }, N=10

Output − Count of only repeated element − 5

Explanation − 4 is repeated 5 times here.

Approach used in the below program is as follows

  • We take an integer array arr[] initialized with consecutive numbers where one number is repeated.

  • Variable len stores the length of the array.

  • Function findRepeat(int arr[],int n) takes an array and its length as input and displays the repeated element value and length of repeated elements.

  • Take the initial count as 0.

  • Starting from index i=0 to i<n. If arr[i]==arr[i+1]. Increment count. Store element in variable value.

  • At the end of loop increment count by 1 for the last element.

  • Display element which is repeated as value.

  • Display number of repetitions as count.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void findRepeat(int arr[],int n){
   int count=0; //count of repeated element
   int value=0; //to store repeated element
   for(int i=0;i<n;i++){
      if(arr[i]==arr[i+1]){
         count++;
         value=arr[i];
      }
   }
   count++; //for last element
   cout<<"Repeated Element: "<<value;
   cout<<endl<<"Number of occurrences: "<<count;
}
int main(){
   int Arr[]={ 2,3,4,5,5,5,6,7,8 };
   int len=sizeof(Arr)/sizeof(Arr[0]);
   findRepeat(Arr,len);
   return 0;
}

Output

If we run the above code it will generate the following output −

Repeated Element: 5
Number of occurrences: 3
raja
Published on 31-Aug-2020 08:20:39
Advertisements