Count consecutive pairs of same elements
Last Updated :
09 Jun, 2022
Given an array arr[], the task is to count the number of pairs formed by consecutive elements in which both of the elements in a pair are same.
Examples:
Input: arr[] = {1, 2, 2, 3, 4, 4, 5, 5, 5, 5}
Output: 5
(1, 2), (4, 5), (6, 7), (7, 8) and (8, 9) are the valid index pairs
where consecutive elements are equal.
Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Output: 0
No two consecutive elements in the given array are equal.
Approach: Initialize count = 0 and traverse the array from arr[0] to arr[n – 2]. If the current element is equal to the next element in the array then increment the count. Print the count in the end.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int countCon( int ar[], int n)
{
int cnt = 0;
for ( int i = 0; i < n - 1; i++) {
if (ar[i] == ar[i + 1])
cnt++;
}
return cnt;
}
int main()
{
int ar[] = { 1, 2, 2, 3, 4, 4, 5, 5, 5, 5 };
int n = sizeof (ar) / sizeof (ar[0]);
cout << countCon(ar, n);
return 0;
}
|
Java
public class GfG
{
static int countCon( int ar[], int n)
{
int cnt = 0 ;
for ( int i = 0 ; i < n - 1 ; i++)
{
if (ar[i] == ar[i + 1 ])
cnt++;
}
return cnt;
}
public static void main(String []args){
int ar[] = { 1 , 2 , 2 , 3 , 4 , 4 , 5 , 5 , 5 , 5 };
int n = ar.length;
System.out.println(countCon(ar, n));
}
}
|
Python3
def countCon(ar, n):
cnt = 0
for i in range (n - 1 ):
if (ar[i] = = ar[i + 1 ]):
cnt + = 1
return cnt
ar = [ 1 , 2 , 2 , 3 , 4 ,
4 , 5 , 5 , 5 , 5 ]
n = len (ar)
print (countCon(ar, n))
|
C#
using System;
class GfG
{
static int countCon( int [] ar, int n)
{
int cnt = 0;
for ( int i = 0; i < n - 1; i++)
{
if (ar[i] == ar[i + 1])
cnt++;
}
return cnt;
}
public static void Main()
{
int [] ar = { 1, 2, 2, 3, 4, 4, 5, 5, 5, 5 };
int n = ar.Length;
Console.WriteLine(countCon(ar, n));
}
}
|
PHP
<?php
function countCon( $ar , $n )
{
$cnt = 0;
for ( $i = 0; $i < $n - 1; $i ++)
{
if ( $ar [ $i ] == $ar [ $i + 1])
$cnt ++;
}
return $cnt ;
}
$ar = array (1, 2, 2, 3, 4, 4, 5, 5, 5, 5);
$n = sizeof( $ar );
echo countCon( $ar , $n );
?>
|
Javascript
<script>
function countCon(ar,n)
{
let cnt = 0;
for (let i = 0; i < n - 1; i++)
{
if (ar[i] == ar[i + 1])
cnt++;
}
return cnt;
}
let ar = [1, 2, 2, 3, 4, 4, 5, 5, 5, 5 ];
let n = ar.length;
document.write(countCon(ar, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...