Largest smaller number possible using only one swap operation | Returns largest possible number with one swap such that the number is smaller than str . It is assumed that there are leading 0 s . ; Traverse from right until we find a digit which is greater than its next digit . For example , in 34125 , our index is 4. ; We can also use binary search here as digits after index are sorted in increasing order . Find the biggest digit in the right of arr [ index ] which is smaller than arr [ index ] ; If index is - 1 i . e . digits are in increasing order . ; Swap both values ; Driver code
function prevNum ( str ) { let len = str . length ; let index = - 1 ; for ( let i = len - 2 ; i >= 0 ; i -- ) { if ( str [ i ] > str [ i + 1 ] ) { index = i ; break ; } } let smallGreatDgt = - 1 ; for ( let i = len - 1 ; i > index ; i -- ) { if ( str [ i ] < str [ index ] ) { if ( smallGreatDgt == - 1 ) { smallGreatDgt = i ; } else if ( str [ i ] >= str [ smallGreatDgt ] ) { smallGreatDgt = i ; } } } if ( index == - 1 ) { return " " ; } if ( smallGreatDgt != - 1 ) { str = swap ( str , index , smallGreatDgt ) ; return str ; } return " " ; } function swap ( str , i , j ) { let ch = str . split ( ' ' ) ; let temp = ch [ i ] ; ch [ i ] = ch [ j ] ; ch [ j ] = temp ; return ch . join ( " " ) ; } let str = " " ; document . write ( prevNum ( str ) ) ;