Lexicographically largest string possible in one swap | Function to return the lexicographically largest string possible by swapping at most one character ; Stores last occurrence of every character ; Initialize with - 1 for every character ; Keep updating the last occurrence of each character ; If a previously unvisited character occurs ; Stores the sorted string ; Character to replace ; Find the last occurrence of this character ; Swap this with the last occurrence ; Driver Code
function findLargest ( s ) { let len = s . length ; let loccur = new Array ( 26 ) ; loccur . fill ( - 1 ) ; for ( let i = len - 1 ; i >= 0 ; -- i ) { let chI = s [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ; if ( loccur [ chI ] == - 1 ) { loccur [ chI ] = i ; } } let sorted_s = s . join ( " " ) . split ( ' ' ) ; sorted_s . sort ( ) ; sorted_s . reverse ( ) ; for ( let i = 0 ; i < len ; ++ i ) { if ( s [ i ] != sorted_s [ i ] ) { let chI = sorted_s [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ; let last_occ = loccur [ chI ] ; let temp = s [ i ] ; s [ i ] = s [ last_occ ] ; s [ last_occ ] = temp ; break ; } } return ( s . join ( " " ) ) ; } let str = " " ; let s = str . split ( ' ' ) ; document . write ( findLargest ( s ) ) ;