Given an string find the minimum number of moves to reach the character with largest and the smallest ASCII value given that in every turn you can only take a step either from leftmost side or rightmost side of string and all characters in string are unique
Examples :
Input : s = AEDCB, N = 5 Output : 2 Explanation : take two steps from leftmost side to reach A and E Input : s = 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 : s = CDBA N = 4 Output : 3 Explanation : take three steps from rightmost side to reach A and then D
Approach :
Follow the steps below to solve the problem:
- Find index of maximum and minimum element in string
- Calculate minimum and maximum of these index to find the min_steps and max_steps that can be taken
- There are only three possible ways to reach both element >>traverse from the start and cover both elements i.e max_steps+1 >>traverse from the last and cover both elements i.e n-min_steps >>traverse from both start and end i.e min_steps+1+n-max_steps
- Final answer is minimum of all possible three ways of traversal
Implementation :
#include <bits/stdc++.h>
using namespace std;
int min_moves(string s, int n)
{
int maxpos = 0, minpos = 0;
// finding index of maximum and minimum element in string
for (int i = 0; i < n; i++) {
if (s[i] > s[maxpos])
maxpos = i;
if (s[i] < s[minpos])
minpos = i;
}
// calculating minimum ans maximum steps that can be
// taken
int min_steps = min(maxpos, minpos);
int max_steps = max(maxpos, minpos);
// only three possible ways to raech both elements
int ans1, ans2, ans3;
ans1 = n - min_steps;
ans2 = max_steps + 1;
ans3 = min_steps + 1 + n - max_steps;
int result;
// minimum steps in all three ways
result = min(ans1, min(ans2, ans3));
return result;
}
// Driver code
int main()
{
string s="BACDEFHG";
int size = s.length();
int x = min_moves(s, size);
cout << x << endl;
return 0;
}
Time Complexity : O(N)
Auxiliary Space : O(1)