Minimum moves to reach from i to j in a cyclic string | C ++ implementation of the approach ; Function to return the count of steps required to move from i to j ; Starting from i + 1 ; Count of steps ; Current character ; If current character is different from previous ; Increment steps ; Update current character ; Return total steps ; Function to return the minimum number of steps required to reach j from i ; Swap the values so that i <= j ; Steps to go from i to j ( left to right ) ; While going from i to j ( right to left ) First go from i to 0 then from ( n - 1 ) to j ; If first and last character is different then it 'll add a step to stepsToLeft ; Return the minimum of two paths ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getSteps ( string str , int i , int j , int n ) { int k = i + 1 ; int steps = 0 ; char ch = str [ i ] ; while ( k <= j ) { if ( str [ k ] != ch ) { steps ++ ; ch = str [ k ] ; } k ++ ; } return steps ; } int getMinSteps ( string str , int i , int j , int n ) { if ( j < i ) { int temp = i ; i = j ; j = temp ; } int stepsToRight = getSteps ( str , i , j , n ) ; int stepsToLeft = getSteps ( str , 0 , i , n ) + getSteps ( str , j , n - 1 , n ) ; if ( str [ 0 ] != str [ n - 1 ] ) stepsToLeft ++ ; return min ( stepsToLeft , stepsToRight ) ; } int main ( ) { string str = " SSNSS " ; int n = str . length ( ) ; int i = 0 , j = 3 ; cout << getMinSteps ( str , i , j , n ) ; return 0 ; }