Given two strings X and Y both consisting of N uppercase alphabets and an integer K, the task is to find the minimum count of cyclic increments of any character in the string X by 1 or K required to convert the string X into string Y.
Cyclic Increments: Incrementing character ‘Z’ by 1 or K starts from the character ‘A’.
Input: X = “ABCT”, Y = “PBDI”, K = 13
Convert the character A to P. Increments required are 13 (A to N), 1 (N to O), 1 (O to P). Therefore, the total count is 3.
Character B remains unchanged. Therefore, the total count remains 3.
Convert the character C to D. Increments required are 1 (C to D). Therefore, the total count is 4.
Convert the character T to I. Increments required is of 13 (T to G), 1 (G to H), 1 (H to I). Therefore, the total count is 7.
Input: X = “ABCD”, Y = “ABCD”, K = 6
Approach: Follow the below steps to solve this problem:
- Initialize a variable, say count, to store the minimum increment required to convert string X into string Y.
- Traverse the string X and for every character in string X, there are three following cases:
- When characters in both the strings X and Y are the same then continue.
- When characters in the string Y is greater than X string then add the value (Y[i] – X[i])/K and (Y[i] – X[i]) modulo K to the count.
- When characters in string X is greater than string Y then subtract the character X[i] from 90 and subtract 64 from Y[i] to calculate the cyclic difference and then add the difference modulo K and difference/K to the count.
- After completing the above steps, print count as the minimum number of increments required.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
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.