Maximize count of distinct strings generated by replacing similar adjacent digits having sum K with K
Given a numeric string S of length N and a digit K, the task is to find the maximum number of distinct strings having a maximum occurrence of K in it formed by replacing any two adjacent digits of S with K if their sum is K.
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.
Input: S = “313”, K = 4
Explanation: Possible strings that can be generated are:
- Replacing S and S with K modifies S to “43”.
- Replacing S and S with K modifies S to “34”.
Input: S = “12352”, K = 7
Explanation: Only string possible is by replacing S and S with K i.e., S = “1237”.
Approach: The given problem can be solved using the observation that for some substring of S, there are two types of possibility to contribute to the result i.e., it can be a sequence of “xy” having an equal number of x and y i.e., “xyxy…xyxy” or it can be a sequence of xy having one extra x i.e., “xyxy…xyxyx” where x + y = K.
- Case 1: String of the form “xyxy…xyxy” can be converted to the string “KK…KK” where K occurs (length of substring)/2 times. So, the number of distinct strings that will be formed is 1.
- Case 2: String of the form “xyxy…xyxyx” has one extra ‘x’ and can be converted into the string “KK…KKx” where K occurs (length of substring-1)/2 times. Let this value is M. Upon observation, it can be seen that there will be (M + 1) possible positions for x in the converted string.
Follow the below steps to solve the problem:
- Initialize the variables ans with 1, flag with 0, and start_index with -1 where ans will store the answer up to index i and start_index will be used to store the starting index of each substring from where the desired sequence started.
- Traverse the string S and do the following:
- If the sum of any adjacent digits S[i] and S[i + 1] is K and flag is set to false, set flag to true and start_index to i.
- If flag is true and S[i] and S[i + 1] is not K, set flag to false and also, if (start_index – i + 1) is odd, multiply ans by (start_index – i + 1 – 1)/2 + 1 as stated in Case 2.
- After traversing the string S, if flag is true and (N – start_index) is odd, multiply ans by (N – start_index – 1)/2 + 1.
- After completing the above steps, print ans as the required answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)