Minimum removals required such that given string consists only of a pair of alternating characters | Function to find the maximum length of alternating occurrences of a pair of characters in a string s ; Stores the next character for alternating sequence ; Stores the length of alternating occurrences of a pair of characters ; Traverse the given string ; If current character is same as the required character ; Increase length by 1 ; Reset required character ; Return the length ; Function to find minimum characters required to be deleted from S to obtain an alternating sequence ; Stores maximum length of alternating sequence of two characters ; Stores length of the string ; Generate every pair of English alphabets ; Function call to find length of alternating sequence for current pair of characters ; Update len to store the maximum of len and newLen in len ; Return n - len as the final result ; Given Input ; Function call to find minimum characters required to be removed from S to make it an alternating sequence of a pair of characters
function findLength ( s , i , j ) { var required = i ; let length = 0 ; for ( let k = 0 ; k < s . length ; k ++ ) { var curr = s . charAt ( k ) ; if ( curr == required ) { length += 1 ; if ( required == i ) required = j ; else required = i ; } } return length ; } function minimumDeletions ( S ) { let len = 0 ; let n = S . length ; for ( let i = 0 ; i < 26 ; i ++ ) { for ( let j = i + 1 ; j < 26 ; j ++ ) { let newLen = findLength ( S , String . fromCharCode ( i + 97 ) , String . fromCharCode ( j + 97 ) ) ; len = Math . max ( len , newLen ) ; } } return n - len ; } let S = " " ; document . write ( minimumDeletions ( S ) ) ;