Count of sub-sequences which satisfy the given condition
Given a string str consisting of digits, the task is to find the number of possible 4 digit sub-sequences which are of the form (x, x, x + 1, x + 1) where x can be from the range [0, 8].
Input: str = “1122”
Only one sub-sequence is valid, i.e the entire string itself.
Input: str = “13134422”
Two Valid sub-sequences are present “1122” and “3344”.
- We will find out total number of possible sub-sequences for each possible x from 0 to 8.
- For each x, remove all other digits from the String, except x and x+1 as they do not affect the answer.
- Maintain a prefix Sum array to count the number of x+1 digits till i th index in the String.
- Now, for every club of digits say size K (which are x), we can choose two numbers in KC2 ways. Last two numbers can be any two numbers from all the digits (which are x+1) which follows that club of digits (count is determined using Prefix Sum Array) say size L, so there are LC2 ways to choose. Total Ways = KC2 * LC2 .
- Till, Now we can be considered x to come from the same club, but it can also be from multiple Clubs. So, we have to consider all possible pairs of clubs and multiply their size to get number of ways to choose first two numbers. For last two numbers, ways will remain same.
- In order to prevent the problem of over counting in Step 5. Only Possible way which includes the current club under consideration will be chosen as other have already been considered in calculation of previous clubs.
- Add all the ways possible for all the values of x and take Modulo.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.