Given string str, a character ch, and an integer K, the task is to find the minimum number of operations required to convert all the characters of string str to ch. Each operation involves converting K closest characters from each side of the index i, i.e., characters in the indices [i – K, i + K] can be converted to ch. Note: Each index can be part of a single operation only. Examples:
Input: str = “abcsdx”, K = 2, ch = ‘#’ Output: 2 Explanation: Operation 1: Select i = 1, therefore, str = “abcsdx” modifies to “###sdx”. Operation 2: Select i = 6, therefore, str = “###sdx” modifies to “######”.
Input: str = “Hellomypkfsg”, k = 3, ch = ‘$’ Output:2 Explanation: Operation 1: Select i = 2, therefore, str = “Hellomypkfsg” modifies to “$$$$$mypkfsg”. Operation 2: Select i = 9, therefore, str = “$$$$$mypkfsg” modifies to “$$$$$$$$$$$$”.
Approach: Follow the steps below to solve the problem:
For any index i, the maximum number of characters that can be converted is 2 * K + 1. Therefore, if the total number of characters in the string does not exceed 2 * K, a single operation is required only to convert the entire string into ch.
Otherwise, the number of operations required will be ceil(n / (2*k+1)).
Iterate over the string, starting from the leftmost possible index that can be used for the operation, and print every (2*k+1)th index after it.
Below is the implementation of the above approach:
Please Login to comment...