How to find Lexicographically previous permutation ? | Function to compute the previous permutation ; Find index of the last element of the string ; Find largest index i such that str [ i - 1 ] > str [ i ] ; If string is sorted in ascending order we 're  at the last permutation ; Note - str [ i . . n ] is sorted in ascending order Find rightmost element 's index  that is less than str[i - 1] ; Swap character at i - 1 with j ; Reverse the substring [ i . . n ] str . reverse ( ) ; ; Driver code
function prevPermutation ( str ) { let n = str . length - 1 ; let i = n ; while ( i > 0 && str [ i - 1 ] . charCodeAt ( 0 ) <= str [ i ] . charCodeAt ( 0 ) ) { i -- ; } if ( i <= 0 ) { return false ; } let j = i - 1 ; while ( j + 1 <= n && str [ j + 1 ] . charCodeAt ( 0 ) <= str [ i - 1 ] . charCodeAt ( 0 ) ) { j ++ ; } let temp = str [ i - 1 ] ; str [ i - 1 ] = str [ j ] ; str [ j ] = temp ; return true ; } let str = " " . split ( " " ) ; if ( prevPermutation ( str ) ) { document . write ( " " + ( str ) . join ( " " ) ) ; } else { document . write ( " " + " " ) ; }