Sort a string lexicographically by reversing a substring | JavaScript program for the above approach ; Function to find the substring in S required to be reversed ; Stores the size of the string ; Stores the starting point of the substring ; Iterate over the string S while i < N ; Increment the value of i ; Stores the ending index of the substring ; If start <= 0 or i >= N ; If start >= 1 and i <= N ; Return the boolean value ; If start >= 1 ; Return the boolean value ; If i < N ; Return true if S [ start ] is less than or equal to S [ i ] ; Otherwise ; Function to check if it is possible to sort the string or not ; Stores the starting and the ending index of substring ; Stores whether it is possible to sort the substring ; Traverse the range [ 1 , N ] ; If S [ i ] is less than S [ i - 1 ] ; If flag stores true ; If adjust ( S , i , start , end ) return false ; Print - 1 ; Unset the flag ; Otherwise ; Print - 1 ; If start is equal to - 1 ; Update start and end ; Print the value of start ; Driver code
var i , start , end ; function adjust ( S ) { var N = S . length ; start = i - 1 ; while ( i < N && S [ i ] < S [ i - 1 ] ) { i ++ ; } end = i - 1 ; if ( start <= 0 && i >= N ) return true ; if ( start >= 1 && i <= N ) { return S [ end ] >= S [ start - 1 ] && S [ start ] <= S [ i ] ; } if ( start >= 1 ) { return S [ end ] >= S [ start - 1 ] ; } if ( i < N ) { return S [ start ] <= S [ i ] ; } return false ; } function isPossible ( S , N ) { start = - 1 ; end = - 1 ; var flag = true ; for ( i = 1 ; i < N ; i ++ ) { if ( S [ i ] < S [ i - 1 ] ) { if ( flag ) { if ( adjust ( S ) === false ) { document . write ( - 1 ) ; return ; } flag = false ; } else { document . write ( - 1 ) ; return ; } } } if ( start === - 1 ) { start = end = 1 ; } document . write ( start + " " + end + " " ) ; } var S = " " ; var N = S . length ; isPossible ( S , N ) ;