Minimum moves to reach from i to j in a cyclic string | 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
< ? php function getSteps ( $ str , $ i , $ j , $ n ) { $ k = $ i + 1 ; $ steps = 0 ; $ ch = $ str [ $ i ] ; while ( $ k <= $ j ) { if ( $ str [ $ k ] != $ ch ) { $ steps ++ ; $ ch = $ str [ $ k ] ; } $ k ++ ; } return $ steps ; } function getMinSteps ( $ str , $ i , $ j , $ n ) { if ( $ j < $ i ) { $ temp = $ i ; $ i = $ j ; $ j = $ temp ; } $ stepsToRight = getSteps ( $ str , $ i , $ j , $ n ) ; $ stepsToLeft = getSteps ( $ str , 0 , $ i , $ n ) + getSteps ( $ str , $ j , $ n - 1 , $ n ) ; if ( $ str [ 0 ] != $ str [ $ n - 1 ] ) $ stepsToLeft ++ ; return min ( $ stepsToLeft , $ stepsToRight ) ; } $ str = " SSNSS " ; $ n = strlen ( $ str ) ; $ i = 0 ; $ j = 3 ; echo getMinSteps ( $ str , $ i , $ j , $ n ) ; ? >