Largest smaller number possible using only one swap operation | PHP program to find the largest smaller number by swapping one digit . 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 ; swap ( str [ index ] , str [ smallGreatDgt ] ) ; ; Driver code
< ? php function prevNum ( $ str ) { $ len = strlen ( $ str ) ; $ index = -1 ; for ( $ i = $ len - 2 ; $ i >= 0 ; $ i -- ) { if ( $ str [ $ i ] > $ str [ $ i + 1 ] ) { $ index = $ i ; break ; } } $ smallGreatDgt = -1 ; for ( $ 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 " - 1" ; if ( $ smallGreatDgt != -1 ) { list ( $ str [ $ index ] , $ str [ $ smallGreatDgt ] ) = array ( $ str [ $ smallGreatDgt ] , $ str [ $ index ] ) ; return $ str ; } return " - 1" ; } $ str = "34125" ; echo prevNum ( $ str ) ; ? >