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 ]
$ 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 ; } }