VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-distinct-original-strings/

⇱ Count distinct original Strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count distinct original Strings

Last Updated : 23 Jul, 2025

Given a string str. A faulty machine prints bb instead of character a and prints dd instead of char c and for the rest characters it prints normally, the task is to find how many distinct original strings could result in the given string. Since the answer can be large print ans modulo 1e9+7.

Examples:

Input: str = "gfgbbndd"
Output: 4
Explanation: Following strings result in str when the faulty machine prints it.

  • gfgandd -> gfgbbndd
  • gfganc -> gfgbbndd
  • gfgbbnc -> gfgbbndd
  • gfgbbndd -> gfgbbndd

Approach: To solve the problem follow the below idea:

We can use Dynamic Programming here, whenever we encounter double b (bb ) or double d (dd) we can generate 2 strings

  • We write the recurrence relation as:
  • If we get two consecutive b or two consecutive d then
    • if we take two consecutive b or consecutive d then we will have to move to index i+2
  • We also have the choice to consider a single character so we include this case as well and take a single character and move to index i +1
  • Else if we don't have both the consecutive characters equal to b or d then we can simply move to index i+1 as we don't have any choice.
  • Finally, we take modulo at each step
  • Edge case if the string contains 'a' or 'c' then it's not possible.

Below is the implementation of above idea:


Output
4

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment