Given a string S of length N and an integer P denoting a pointer to Pth index of the string, the task is to find the minimum cost to convert the string into a palindrome by performing the following operations:
Pointer P can be moved from index i to index j and the cost required is |i – j| where 0 ≤ i < N and 0 ≤ j < N.
The cost to change the character at the Pth index is 1.
Input: S = “saad”, P = 1 Output: 2 Explanation: Initially the pointer is at index 1. Step 1: Move pointer to index 0. Therefore, cost = 1 – 0 = 1. Step 2: Change character s to d. Therefore, cost = 1 + 1 = 2 and S = “daad” Hence, the cost is 2.
Input: S = “bass”, P = 3 Output: 3 Explanation: Initially the pointer is at index 3. Step 1: Change character at index P = 3 to b. Therefore, cost = 1 and S = “basb”. Step 2: Move pointer to index 2. Therefore, cost = 1 + 1 = 2. Step 3: Change character at index P = 2 to a. Therefore, cost = 3 and S = “baab” Hence, the cost is 3.
Approach: The idea is to find the first and the last character that needs to be changed in the first half of the string when the pointer is in the first half or reverse the string if the pointer is in the second half and adjust the pointer accordingly. Follow the below steps to solve the problem:
If the pointer is in the second half then reverse the string and change the pointer to (N – 1 – P).
Now, find the farthest character’s position needed to change at the left and right side in the first half of the string. Let them be l and r.
Find the total cost to change the characters i.e., total characters in the first half such that S[i] != s[N – i – 1] where 0 < i < N/2.
The minimum distance traverse to change the characters is min(2*(P – l) + r – P, 2*(r – P) + P – l).
Print the answer as the sum of the cost to change the characters and minimum distance to travel.
Below is the implementation of the above approach:
Please Login to comment...