Minimum number of elements to be removed so that pairwise consecutive elements are same
Given a string str. The task is to count the minimum number of elements to be removed so that pairwise consecutive elements are same
Examples:
Input : str = “11344”
Output: 1
Remove the digit 3 from 3rd place so that the string becomes 1144. Thus pairwise two consecutive elements are same. Hence answer is 1.
Input : str = “55553”
Output : 1
Remove the digit 3 from the 5th place so that the string becomes 5555. Thus pairwise two consecutive elements are same. Hence answer is 1.
Approach: Check if the current two consecutive elements are same or not. If yes then increment the index by 2 and keep checking till all the elements get traversed. Else increment the index by 1 and count by 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countConsecutive(string s)
{
int count = 0;
for ( int i = 0; i < s.size(); i++) {
if (s[i] == s[i + 1])
i++;
else
count++;
}
return count;
}
int main()
{
string str = "44522255" ;
cout << countConsecutive(str);
return 0;
}
|
Java
class GFG {
static int countConsecutive(String s) {
int count = 0 ;
for ( int i = 0 ; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i + 1 )) {
i++;
} else {
count++;
}
}
return count;
}
public static void main(String args[]) {
String str = "44522255" ;
System.out.println(countConsecutive(str));
}
}
|
Python3
def countConsecutive(s):
count = - 1
for i in range ( len (s) - 1 ):
if (i < = len (s)):
if (s[i] is s[i + 1 ]):
i + = 1
else :
count + = 1
return count
if __name__ = = '__main__' :
str = "44522255"
print (countConsecutive( str ))
|
C#
using System;
public class GFG {
static int countConsecutive(String s) {
int count = 0;
for ( int i = 0; i < s.Length; i++) {
if (s[i] == s[i+1]) {
i++;
} else {
count++;
}
}
return count;
}
public static void Main() {
String str = "44522255" ;
Console.WriteLine(countConsecutive(str));
}
}
|
PHP
<?php
function countConsecutive( $s )
{
$count = 0;
for ( $i = 0; $i < strlen ( $s ); $i ++)
{
if ( $s [ $i ] == $s [ $i + 1])
$i ++;
else
$count ++;
}
return $count ;
}
$str = "44522255" ;
echo countConsecutive( $str );
?>
|
Javascript
<script>
function countConsecutive(s)
{
let count = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] == s[i + 1])
i++;
else
count++;
}
return count;
}
let str = "44522255" ;
document.write(countConsecutive(str));
</script>
|
Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(1)
Last Updated :
07 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...