Count of distinct possible strings after performing given operations
Last Updated :
20 Oct, 2023
Given a numeric string S consisting of only three types of characters 0, 1, and 2 initially and following two operations:
- The occurrence of two consecutive 1 can be replaced by 3.
- The occurrence of two consecutive 2 can be replaced by 4.
The given task is to find the total number of different strings that can be formed by using the operations.
Examples:
Input: S = "0110000022"
Output: 4
Explanation:
There can be four different formed by using the operations, the four strings are
"0110000022", "030000022", "03000004", "011000004"
Input: S = "111"
Output: 3
Approach:
In order to solve this problem, we are using a dynamic programming approach. We define an array dp to store the count of possible strings of length equal to its respective indices.
- Initialize dp[0] = dp[1] = 1.
- For any index i between [1, N-1], if the character at that index is '1' or '2' and is equal to that of its previous index, add the possible strings that can be formed of length i-1 and i-2. Otherwise, it is the same as that of length i-1.
dp[i + 1] = dp[i] + dp[i-1] if S[i] == S[i-1] where S[i] is either '1' or '2'.
dp[i + 1] = dp[i] otherwise.
- Return dp[n] as the count of different strings possible.
Below is the implementation of the above approach:
C++
// C++ implementation of
// the above approach
#include
using namespace std;
// Function that prints the
// number of different strings
// that can be formed
void differentStrings(string s)
{
// Computing the length of
// the given string
int n = s.length();
vector dp(n + 1);
// Base case
dp[0] = dp[1] = 1;
// Traverse the given string
for (int i = 1; i < n; i++) {
// If two consecutive 1's
// or 2's are present
if (s[i] == s[i - 1]
&& (s[i] == '1'
|| s[i] == '2'))
dp[i + 1]
= dp[i] + dp[i - 1];
// Otherwise take
// the previous value
else
dp[i + 1] = dp[i];
}
cout << dp[n] << "\n";
}
// Driver Code
int main()
{
string S = "0111022110";
differentStrings(S);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void differentStrings(char* s)
{
// Computing the length of
// the given string
int n = strlen(s);
int dp[n + 1];
// Base case
dp[0] = dp[1] = 1;
// Traverse the given string
for (int i = 1; i < n; i++) {
// If two consecutive 1's
// or 2's are present
if (s[i] == s[i - 1]
&& (s[i] == '1'
|| s[i] == '2'))
dp[i + 1] = dp[i] + dp[i - 1];
// Otherwise take
// the previous value
else
dp[i + 1] = dp[i];
}
printf("%d\n", dp[n]);
}
// Driver Code
int main()
{
char S[] = "0111022110";
differentStrings(S);
return 0;
}
// This code is contributed by phalashi.
Java
// Java implementation of the above approach
import java.io.*;
class GFG{
// Function that prints the
// number of different strings
// that can be formed
static void differentStrings(String s)
{
// Computing the length of
// the given string
int n = s.length();
int[] dp = new int[n + 1];
// Base case
dp[0] = dp[1] = 1;
// Traverse the given string
for(int i = 1; i < n; i++)
{
// If two consecutive 1's
// or 2's are present
if (s.charAt(i) == s.charAt(i - 1) &&
(s.charAt(i) == '1' ||
s.charAt(i) == '2'))
dp[i + 1] = dp[i] + dp[i - 1];
// Otherwise take the
// previous value
else
dp[i + 1] = dp[i];
}
System.out.println(dp[n]);
}
// Driver code
public static void main(String[] args)
{
String S = "0111022110";
differentStrings(S);
}
}
// This code is contributed by offbeat
Python3
# Python3 implementation of
# the above approach
# Function that prints the
# number of different strings
# that can be formed
def differentStrings(s):
# Computing the length of
# the given string
n = len(s)
dp = [0] * (n + 1)
# Base case
dp[0] = dp[1] = 1
# Traverse the given string
for i in range (1, n):
# If two consecutive 1's
# or 2's are present
if (s[i] == s[i - 1] and
(s[i] == '1' or
s[i] == '2')):
dp[i + 1] = dp[i] + dp[i - 1]
# Otherwise take
# the previous value
else:
dp[i + 1] = dp[i]
print (dp[n])
# Driver Code
if __name__ == "__main__":
S = "0111022110"
differentStrings(S)
# This code is contributed by Chitranayal
C#
// C# implementation of the above approach
using System;
class GFG{
// Function that prints the
// number of different strings
// that can be formed
static void differentStrings(string s)
{
// Computing the length of
// the given string
int n = s.Length;
int[] dp = new int[n + 1];
// Base case
dp[0] = dp[1] = 1;
// Traverse the given string
for(int i = 1; i < n; i++)
{
// If two consecutive 1's
// or 2's are present
if (s[i] == s[i - 1] &&
(s[i] == '1' ||
s[i] == '2'))
dp[i + 1] = dp[i] + dp[i - 1];
// Otherwise take the
// previous value
else
dp[i + 1] = dp[i];
}
Console.Write(dp[n]);
}
// Driver code
public static void Main()
{
string S = "0111022110";
differentStrings(S);
}
}
// This code is contributed by Code_Mech
JavaScript
<script>
// JavaScript implementation of
// the above approach
// Function that prints the
// number of different strings
// that can be formed
function differentStrings(s)
{
// Computing the length of
// the given string
var n = s.length;
var dp = Array(n + 1);
// Base case
dp[0] = dp[1] = 1;
// Traverse the given string
for (var i = 1; i < n; i++) {
// If two consecutive 1's
// or 2's are present
if (s[i] == s[i - 1]
&& (s[i] == '1'
|| s[i] == '2'))
dp[i + 1]
= dp[i] + dp[i - 1];
// Otherwise take
// the previous value
else
dp[i + 1] = dp[i];
}
document.write( dp[n] + "<br>");
}
// Driver Code
var S = "0111022110";
differentStrings(S);
</script>
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time
Auxiliary Space: O(N), as we are using extra space for DP array.
Efficient approach : Space optimization O(1)
In previous approach we the current value dp[i] is only depend upon the previous 2 values i.e. dp[i-1] and dp[i+1]. So to optimize the space we can keep track of previous and next values by the help of three variables prev and next which will reduce the space complexity from O(N) to O(1).
Implementation Steps:
- Create 2 variables prev1 and prev2 to keep track o previous values of DP.
- Initialize base case prev = curr = 1.
- Create a variable curr to store current value.
- Iterate over subproblem using loop and update curr.
- Create variable next to keep track of next value of DP.
- After every iteration update prev and curr for further iterations.
- At last return curr.
Implementation:
C++
#include <iostream>
using namespace std;
// Function that prints the
// number of different strings
// that can be formed
void differentStrings(string s)
{
// Computing the length of
// the given string
int n = s.length();
// Base case
int prev = 1, curr = 1;
// Traverse the given string
for (int i = 1; i < n; i++) {
// If two consecutive 1's
// or 2's are present
if (s[i] == s[i - 1]
&& (s[i] == '1'
|| s[i] == '2')) {
int next = prev + curr;
prev = curr;
curr = next;
}
// Otherwise take
// the previous value
else {
prev = curr;
}
}
cout << curr << "\n";
}
// Driver Code
int main()
{
string S = "0111022110";
differentStrings(S);
return 0;
}
Java
import java.util.*;
public class Main {
// Utility function to find the number of different strings
// that can be formed
public static void differentStrings(String s)
{
// Computing the length of the given string
int n = s.length();
// Base case
int prev = 1, curr = 1;
// Traverse the given string
for (int i = 1; i < n; i++) {
// If two consecutive 1's or 2's are present
if (s.charAt(i) == s.charAt(i - 1)
&& (s.charAt(i) == '1' || s.charAt(i) == '2')) {
int next = prev + curr;
prev = curr;
curr = next;
}
// Otherwise take the previous value
else {
prev = curr;
}
}
System.out.println(curr);
}
// Driver Code
public static void main(String[] args) {
String S = "0111022110";
differentStrings(S);
}
}
Python3
def different_strings(s: str) -> None:
# Computing the length of the given string
n = len(s)
# Base case
prev, curr = 1, 1
# Traverse the given string
for i in range(1, n):
# If two consecutive 1's or 2's are present
if s[i] == s[i - 1] and (s[i] == '1' or s[i] == '2'):
next = prev + curr
prev = curr
curr = next
# Otherwise take the previous value
else:
prev = curr
print(curr)
# Driver Code
if __name__ == '__main__':
S = "0111022110"
different_strings(S)
C#
using System;
public class Program
{
// Utility function to find the number of different strings
// that can be formed
public static void DifferentStrings(string s)
{
// Computing the length of the given string
int n = s.Length;
// Base case
int prev = 1, curr = 1;
// Traverse the given string
for (int i = 1; i < n; i++)
{
// If two consecutive 1's or 2's are present
if (s[i] == s[i - 1] && (s[i] == '1' || s[i] == '2'))
{
int next = prev + curr;
prev = curr;
curr = next;
}
// Otherwise take the previous value
else
{
prev = curr;
}
}
Console.WriteLine(curr);
}
// Entry point
public static void Main(string[] args)
{
string S = "0111022110";
DifferentStrings(S);
}
}
// This code is contributed by Dwaipayan Bandyopadhyay
JavaScript
// Function that prints the
// number of different strings
// that can be formed
function differentStrings(s) {
// Computing the length of
// the given string
const n = s.length;
// Base case
let prev = 1, curr = 1;
// Traverse the given string
for (let i = 1; i < n; i++) {
// If two consecutive 1's
// or 2's are present
if (s[i] === s[i - 1] && (s[i] === '1' || s[i] === '2')) {
const next = prev + curr;
prev = curr;
curr = next;
} else {
// Otherwise take
// the previous value
prev = curr;
}
}
console.log(curr);
}
// Driver Code
const S = "0111022110";
differentStrings(S);
Output:
12
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time
Auxiliary Space: O(1)
Similar Reads
Count of distinct groups of strings formed after performing equivalent operation
Given an array arr[] of N strings consisting of lowercase alphabets, the task is to find the number of distinct groups of strings formed after performing the equivalent operation. Two strings are said to be equivalent if there exists the same character in both the strings and if there exists another
12 min read
Count of Distinct strings possible by inserting K characters in the original string
Given a string S and an integer K, the task is to find the total number of strings that can be formed by inserting exactly K characters at any position of the string S. Since the answer can be large, print it modulo 109+7.Examples: Input: S = "a" K = 1 Output: 51 Explanation: Since any of the 26 cha
12 min read
Count of Distinct Substrings occurring consecutively in a given String
Given a string str, the task is to find the number of distinct substrings that are placed consecutively in the given string. Examples: Input: str = "geeksgeeksforgeeks" Output: 2 Explanation: geeksgeeksforgeeks -> {"geeks"} geeksgeeksforgeeks -> {"e"} Only one consecutive occurrence of "e" is
14 min read
Perform range sum queries on string as per given condition
Given a string S with lowercase alphabets only and Q queries where each query contains a pair {L, R}. For each query {L, R}, there exists a substring S[L, R], the task is to find the value of the product of the frequency of each character in substring with their position in alphabetical order. Note:
7 min read
Count number of distinct substrings of a given length
Given a string S of length N consisting of lower-case English alphabets and an integer 'l', find the number of distinct substrings of length 'l' of the given string. Examples: Input : s = "abcbab", l = 2 Output : 4 All distinct sub-strings of length 2 will be {"ab", "bc", "cb", "ba"} Thus, answer eq
6 min read
Count Number of Distinct Binary Strings After Applying Flip Operations
Given a binary string s and a positive integer k. In a operation you can repeatedly choose any substring of length k in s and flip all its characters (0s to 1s, 1s to 0s). The task is to return the number of distinct strings that can be obtained, modulo 10^9 + 7. You can perform the flip operation a
5 min read
Count of distinct strings that can be obtained after performing exactly one swap
Given a string s containing lowercase English alphabet characters. The task is to calculate the number of distinct strings that can be obtained after performing exactly one swap. Input: s = "geek"Output: 6Explanation: Following are the strings formed by doing exactly one swapstrings = ["egek","eegk"
5 min read
Count substrings made up of a single distinct character
Given a string S of length N, the task is to count the number of substrings made up of a single distinct character.Note: For the repetitive occurrences of the same substring, count all repetitions. Examples: Input: str = "geeksforgeeks"Output: 15Explanation: All substrings made up of a single distin
5 min read
Count number of substrings having at least K distinct characters
Given a string S consisting of N characters and a positive integer K, the task is to count the number of substrings having at least K distinct characters.Examples:Input: S = "abcca", K = 3Output: 4Explanation:The substrings that contain at least K(= 3) distinct characters are:"abc": Count of distinc
7 min read
Count distinct substrings of a string using Rabin Karp algorithm
Given a string, return the number of distinct substrings using Rabin Karp Algorithm. Examples: Input : str = âabaâOutput : 5Explanation :Total number of distinct substring are 5 - "a", "ab", "aba", "b" ,"ba" Input : str = âabcdâOutput : 10Explanation :Total number of distinct substring are 10 - "a",
9 min read