Minimum distance between duplicates in a String | This function is used to find minimum distance between same repeating characters ; Define a hashmap and an arraylist ; Temporary variable ; Traverse through string ; If character present in dictionary ; Difference between current position and last stored value ; Updating current position ; Storing difference in list ; If character not in dictionary assign it with initial of its position ; If no element inserted in list i . e . no repeating characterss ; Return minimum distance ; Given input ; Function call
function shortestDistance ( S , N ) { var dic = new Map ( ) ; var dis = new Array ( ) ; var var1 ; for ( i = 0 ; i < N ; i ++ ) { if ( dic [ S [ i ] ] != null ) { var1 = i - dic [ S [ i ] ] ; dic [ S [ i ] ] = i ; dis . push ( var1 ) ; } else { dic [ S [ i ] ] = i ; } } if ( dis . length == 0 ) return - 1 ; else return dis . reduce ( function ( previous , current ) { return previous < current ? previous : current } ) - 1 ; } var S = " " ; var N = 13 ; document . write ( shortestDistance ( S , N ) ) ;