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



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

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

  • 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 
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

Output

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

Repeated Element: 5
Number of occurrences: 3
Updated on: 2020-08-31T08:21:18+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements