Maximum number of characters between any two same character in a string | Efficient javascript program to find maximum number of characters between two occurrences of same character ; Initialize all indexes as - 1. ; If this is first occurrence ; Else find distance from previous occurrence and update result ( if required ) . ; Driver code
let MAX_CHAR = 256 ; function maximumChars ( str ) { let n = str . length ; let res = - 1 ; let firstInd = new Array ( MAX_CHAR ) ; for ( let i = 0 ; i < MAX_CHAR ; i ++ ) firstInd [ i ] = - 1 ; for ( let i = 0 ; i < n ; i ++ ) { let first_ind = firstInd [ str [ i ] . charCodeAt ( 0 ) ] ; if ( first_ind == - 1 ) firstInd [ str [ i ] . charCodeAt ( 0 ) ] = i ; else res = Math . max ( res , Math . abs ( i - first_ind - 1 ) ) ; } return res ; } let str = " " ; document . write ( maximumChars ( str ) ) ;