Open In App

Count of strings possible by replacing two consecutive same character with new character

Last Updated : 04 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given string str. The task is to count the number of all different strings possible if two consecutive same characters of the string can be replaced by one different character.

Examples 

Input: str = “abclll” 
Output:
Explanation: 
There can be 3 different string including the original string as shown in the below figure:- 
 

Input: str = “abcllldefkkkk” 
Output: 15 
Explanation: 
There can be 15 different string including the original string as shown in the below figure:- 
 

Approach: 
The following properties were observed for replacing two equal characters at a time: 

  • If for string = “aaa” of length 3 we replace two “aa” with one character say “K” then the total number of different possible strings including the original string is:- Ka, aK, aaa. Therefore the number of different strings follows the property of Fibonacci Number of the length of the consecutive characters in the string.
  • If string = “aaadefyyyy” then the total number of possible different strings is equaled to the product of combinations of string “aaa” and “yyyy” by replacing the two consecutive characters at a time.

Hence from the above two observations, the count of different possible strings with N consecutive characters is given by N-th Fibonacci Number. Therefore, the total number of different possible strings for the given string str is equal to the product of count of different possible strings for every substring with all same characters.

The following are the steps: 

  • Count(say cnt) the number of consecutive characters which are same in the given string str.
  • To count the different possible strings for the count cnt, find the value of Fibonacci Sequence at cnt.
  • Repeat the above steps for all the consecutive characters in the given string str.
  • The total count of different possible strings is equaled to the product of all the value of Fibonacci Sequence obtained for every count of consecutive characters.

Below is the implementation of the above approach: 

C++




// C++ program to count the
// different possible string
// form by replacing two same
// characters with one
#include <bits/stdc++.h>
using namespace std;
 
// Array to find the fibonacci
// sequence
int fib[100005];
 
// Function to find the
// fibonacci sequence
void computeFibonacci()
{
    fib[0] = 1;
    fib[1] = 1;
    for (int i = 2; i < 100005; i++) {
        fib[i] = fib[i - 1] + fib[i - 2];
    }
}
 
// Function to count all
// possible strings
int countString(string str)
{
 
    // Initialize ans = 1
    int ans = 1;
    int cnt = 1;
 
    for (int i = 1; str[i]; i++) {
 
        // If two consecutive
        // char are same
        // increase cnt
        if (str[i] == str[i - 1]) {
            cnt++;
        }
 
        // Else multiply the
        // fib[cnt] to ans
        // and initialize ans
        // to 1
        else {
            ans = ans * fib[cnt];
            cnt = 1;
        }
    }
    //
    // If str = abcdeeee, then
    // for last "eeee" the
    // count munst be updated
    ans = ans * fib[cnt];
 
    // Return the total count
    return ans;
}
 
// Driver's Code
int main()
{
    string str = "abdllldefkkkk";
 
    // Function to precompute
    // all the fibonacci number
    computeFibonacci();
 
    // Function call to find
    // the count
    cout << countString(str);
    return 0;
}


Java




// Java program to count the
// different possible string
// form by replacing two same
// characters with one
class GFG {
     
    // Array to find the fibonacci
    // sequence
    static int fib[] = new int[100005];
     
    // Function to find the
    // fibonacci sequence
    static void computeFibonacci()
    {
        fib[0] = 1;
        fib[1] = 1;
        for (int i = 2; i < 100005; i++) {
            fib[i] = fib[i - 1] + fib[i - 2];
        }
    }
     
    // Function to count all
    // possible strings
    static int countString(String str)
    {
     
        // Initialize ans = 1
        int ans = 1;
        int cnt = 1;
     
        for (int i = 1; i<str.length(); i++) {
     
            // If two consecutive
            // char are same
            // increase cnt
            if (str.charAt(i) == str.charAt(i - 1)) {
                cnt++;
            }
     
            // Else multiply the
            // fib[cnt] to ans
            // and initialize ans
            // to 1
            else {
                ans = ans * fib[cnt];
                cnt = 1;
            }
        }
          
        // If str = abcdeeee, then
        // for last "eeee" the
        // count munst be updated
        ans = ans * fib[cnt];
     
        // Return the total count
        return ans;
    }
     
    // Driver's Code
    public static void main (String[] args)
    {
        String str = "abdllldefkkkk";
     
        // Function to precompute
        // all the fibonacci number
        computeFibonacci();
     
        // Function call to find
        // the count
        System.out.println(countString(str));
    }
}
 
// This code is contributed by Yash_R


Python3




# Python3 program to count the
# different possible string
# form by replacing two same
# characters with one
 
# Array to find the fibonacci
# sequence
fib = [0]*100005;
 
# Function to find the
# fibonacci sequence
def computeFibonacci() :
 
    fib[0] = 1;
    fib[1] = 1;
    for i in range(2, 100005) :
        fib[i] = fib[i - 1] + fib[i - 2];
 
# Function to count all
# possible strings
def countString(string) :
 
    # Initialize ans = 1
    ans = 1;
    cnt = 1;
 
    for i in range(1, len(string)) :
 
        # If two consecutive
        # char are same
        # increase cnt
        if (string[i] == string[i - 1]) :
            cnt += 1;
 
        # Else multiply the
        # fib[cnt] to ans
        # and initialize ans
        # to 1
        else :
            ans = ans * fib[cnt];
            cnt = 1;
             
    # If str = abcdeeee, then
    # for last "eeee" the
    # count munst be updated
    ans = ans * fib[cnt];
 
    # Return the total count
    return ans;
 
# Driver's Code
if __name__ == "__main__" :
 
    string = "abdllldefkkkk";
 
    # Function to precompute
    # all the fibonacci number
    computeFibonacci();
 
    # Function call to find
    # the count
    print(countString(string));
     
# This code is contributed by Yash_R


C#




// C# program to count the
// different possible string
// form by replacing two same
// characters with one
using System;
 
class GFG {
     
    // Array to find the fibonacci
    // sequence
    static int []fib = new int[100005];
     
    // Function to find the
    // fibonacci sequence
    static void computeFibonacci()
    {
        fib[0] = 1;
        fib[1] = 1;
        for (int i = 2; i < 100005; i++) {
            fib[i] = fib[i - 1] + fib[i - 2];
        }
    }
     
    // Function to count all
    // possible strings
    static int countString(string str)
    {
     
        // Initialize ans = 1
        int ans = 1;
        int cnt = 1;
     
        for (int i = 1; i < str.Length; i++) {
     
            // If two consecutive
            // char are same
            // increase cnt
            if (str[i] == str[i - 1]) {
                cnt++;
            }
     
            // Else multiply the
            // fib[cnt] to ans
            // and initialize ans
            // to 1
            else {
                ans = ans * fib[cnt];
                cnt = 1;
            }
        }
          
        // If str = abcdeeee, then
        // for last "eeee" the
        // count munst be updated
        ans = ans * fib[cnt];
     
        // Return the total count
        return ans;
    }
     
    // Driver's Code
    public static void Main (string[] args)
    {
        string str = "abdllldefkkkk";
     
        // Function to precompute
        // all the fibonacci number
        computeFibonacci();
     
        // Function call to find
        // the count
        Console.WriteLine(countString(str));
    }
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
 
// Javascript program to count the
// different possible string
// form by replacing two same
// characters with one    
 
// Array to find the fibonacci
// sequence
     fib = Array(100005).fill(0);
 
    // Function to find the
    // fibonacci sequence
    function computeFibonacci()
    {
        fib[0] = 1;
        fib[1] = 1;
        for (i = 2; i < 100005; i++) {
            fib[i] = fib[i - 1] + fib[i - 2];
        }
    }
 
    // Function to count all
    // possible strings
    function countString( str) {
 
        // Initialize ans = 1
        var ans = 1;
        var cnt = 1;
 
        for (i = 1; i < str.length; i++)
        {
 
            // If two consecutive
            // char are same
            // increase cnt
            if (str.charAt(i) == str.charAt(i - 1))
            {
                cnt++;
            }
 
            // Else multiply the
            // fib[cnt] to ans
            // and initialize ans
            // to 1
            else {
                ans = ans * fib[cnt];
                cnt = 1;
            }
        }
 
        // If str = abcdeeee, then
        // for last "eeee" the
        // count munst be updated
        ans = ans * fib[cnt];
 
        // Return the total count
        return ans;
    }
 
    // Driver's Code
     
        var str = "abdllldefkkkk";
 
        // Function to precompute
        // all the fibonacci number
        computeFibonacci();
 
        // Function call to find
        // the count
        document.write(countString(str));
 
// This code contributed by umadevi9616
 
</script>


Output: 

15

 

Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(M), where M = 100005



Similar Reads

Count distinct strings possible by replacing each character by its Morse code
Given an array of strings arr[], the task is to count the number of distinct strings that can be generated from the given array by replacing each character of the strings by its Morse code. Below is the Morse code of all the lowercase alphabets: Examples: Input: arr[] = {"gig", "zeg", "gin", "msn"}Output: 2Explanation: Replacing each character of t
10 min read
Count possible binary strings of length N without P consecutive 0s and Q consecutive 1s
Given three integers N, P, and Q, the task is to count all possible distinct binary strings of length N such that each binary string does not contain P times consecutive 0’s and Q times consecutive 1's. Examples: Input: N = 5, P = 2, Q = 3Output: 7Explanation: Binary strings that satisfy the given conditions are { “01010”, “01011”, “01101”, “10101”
19 min read
Modify array of strings by replacing characters repeating in the same or remaining strings
Given an array of strings arr[] consisting of lowercase and uppercase characters only, the task is to modify the array by removing the characters from the strings which are repeating in the same string or any other string. Print the modified array. Examples: Input: arr[] = {"Geeks", "For", "Geeks"}Output: {"Geks", "For"}Explanation:In arr[0[, 'e' o
6 min read
Check if given strings can be made same by swapping two characters of same or different strings
Given an array of equal-length strings, arr[] of size N, the task is to check if all the strings can be made equal by repeatedly swapping any pair of characters of same or different strings from the given array. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { "acbdd", "abcee" } Output: YES Explanation: Swapp
11 min read
Make given Binary Strings equal by replacing two consecutive 0s with single 1 repeatedly
Given two binary strings str1 and str2, the task is to check whether it is possible to convert str1 to str2 by combining two consecutive 0's into a single 1 repeatedly. Examples: Input: str1 = "00100", str2 = "111" Output: Yes Explanation: Combine first two zeros to one and combine last two zeros to one. Input: str1 = "00", str2 = "000" Output: No
6 min read
Count pairs of same parity indexed elements with same MSD after replacing each element by the sum of maximum digit * A and minimum digits * B
Given an array arr[] of N 3-digit integers and two integers a and b, the task is to modify each array element according to the following rules: Find the maximum, say M, and minimum digit, say m, of each array element arr[i].Update the array element arr[i] as (A * M + B * m). The task is to count the number of pairs such that the chosen elements are
12 min read
Count of possible distinct Binary strings after replacing "11" with "0"
Given a binary string str of size N containing 0 and 1 only, the task is to count all possible distinct binary strings when a substring "11" can be replaced by "0". Examples: Input: str = "11011"Output: 4Explanation: All possible combinations are "11011", "0011", "1100", "000". Input: str = "110011100011111"Output: 48 Naive Approach: The simplest i
15 min read
Count of possible Strings by replacing consonants with nearest vowel
Given a string str consisting of N letters, the task is to find the total number of strings that can be generated by replacing each consonant with the vowel closest to it in the English alphabet. Examples: Input: str = "code"Output: 2Explanation: Str = "code" has two consonant c and d. Closest vowel to d is e and closest to c are a and e.The possib
4 min read
Count of Binary strings having at most X consecutive 1s and Y consecutive 0s
Given two integers N and M (1 ≤ N, M ≤ 100) denoting the total number of 1s and 0s respectively. The task is to count the number of possible arrangements of these 0s and 1s such that any arrangement has at most X consecutive 1s and Y consecutive 0s (1 ≤ X, Y ≤ 10). As the number of arrangements can be very large, compute the answer with MODULO 109+
7 min read
Count of same length Strings that exists lexicographically in between two given Strings
Given two string S1 and S2 of length L, the task is to count the number of strings of length L, that exists in between S1 and S2, which are lexicographically greater than S1 but smaller than S2. Examples: Input: S1 = "b", S2 = "f" Output: 3 Explanation: These are 3 strings which come lexicographically in between S1 and S2 i.e. "c", "d" &amp; "e"Inp
8 min read