Given a string str, the task is to find the minimum number of moves required to reach lexicographically largest and smallest characters. In one move, a jump can be made from leftmost side or the rightmost side of given string.
Input: str = AEDCB, N = 5 Output: 2 Explanation: take two steps from leftmost side to reach A and E
Input: str = BACDEFHG, N = 8 Output: 4 Explanation: take two steps from leftmost side to reach A and 2 steps from rightmost side to reach H(2+2=4)
Input: str = CDBA, N = 4 Output: 3 Explanation: take three steps from rightmost side to reach A and then D
Approach: This problem is implementation-based. Follow the steps below to solve the given problem.
Find the index of maximum and minimum elements in the string
Calculate the minimum and maximum of these indexes to find the min_steps and max_steps that can be taken
There are only three possible ways to reach both elements
traverse from the start and cover both elements i.e min_steps+1
traverse from the last and cover both elements i.e n-max_steps
traverse from both start and end i.e min_steps+1+n-max_steps
The final answer is a minimum of all possible three ways of traversal.
Below is the implementation of the above approach:
Please Login to comment...