Minimum number of swaps required to make the string K periodic | Javascript code for the above approach . ; Mark all allowed characters as true ; Initialize the freq array to 0 ; Increase the frequency of each character ; Total number of periods of size K in the String ; Check if the current character is present in allowed and whether the current frequency is greater than all previous frequencies for this position ; Update the answer by subtracting the maxfrequency from total positions if there exist extra character at the end of the String apart from the n / k characters then add 1. ; Driver code
function minFlip ( s , n , k , a , p ) { let allowed = Array . from ( { length : 26 } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < p ; i ++ ) { allowed [ a [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] = true ; } let freq = new Array ( k ) ; for ( var i = 0 ; i < freq . length ; i ++ ) { freq [ i ] = new Array ( 2 ) ; } for ( let i = 0 ; i < k ; i ++ ) for ( let j = 0 ; j < 26 ; j ++ ) freq [ i ] [ j ] = 0 ; for ( let i = 0 ; i < n ; i ++ ) { freq [ i % k ] [ s [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] += 1 ; } let ans = 0 ; let totalpositions = Math . floor ( n / k ) ; for ( let i = 0 ; i < k ; i ++ ) { let maxfrequency = 0 ; for ( let j = 0 ; j < 26 ; j ++ ) { if ( freq [ i ] [ j ] > maxfrequency && allowed [ j ] == true ) maxfrequency = freq [ i ] [ j ] ; } ans += ( totalpositions - maxfrequency + ( ( i % k < n % k ) ? 1 : 0 ) ) ; } document . write ( ans + " " ) ; } let S = " " ; let n = S . length ; let K = 3 ; let A = [ ' ' , ' ' , ' ' , ' ' , ' ' ] ; let p = A . length ; minFlip ( S , n , K , A , p ) ;