Minimum moves to reach the smallest and largest character

Updated

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:

  1. Find index of maximum and minimum element in string
  2. Calculate minimum and maximum of these index to find the min_steps and max_steps  that can be taken
  3. 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
  4. 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;
}
Output

4

Time Complexity : O(N)

Auxiliary Space : O(1)

Comment
Mithlesh Upadhyay Published 24 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials