Number of indexes with equal elements in given range in C++


You are given an array, and indexes range. You need to count the total number of adjacent elements that are equal in the given range.

Let's see an example.

Input

arr = [1, 2, 2, 2, 3, 3, 4]
lower = 1
upper = 5

Output

3

Algorithm

  • Initialise the array and indexes range.

  • Write a loop that iterates from the lower index of the range to upper index of the range.

    • Compare the element the previous or next element.

    • Increment the count if they are equal.

  • Return the count.

Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
int getEqualElementsCount(int arr[], int n, int lower, int upper) {
   int count = 0;
   for (int i = lower; i < upper; i++) {
      if (arr[i] == arr[i + 1]) {
         count += 1;
      }
   }
   return count;
}
int main() {
   int arr[] = { 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5 };
   int n = 15;
   cout << getEqualElementsCount(arr, 15, 1, 15) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

10

Updated on: 26-Oct-2021

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements