codeparrot/xlcost-text-to-code huggingface dataset:
Cube Free Numbers smaller than n | Returns true if n is a cube free number , else returns false . ; Check for all possible divisible cubes ; Print all cube free numbers smaller than n . ; Driver code
function isCubeFree ( n ) { if ( n == 1 ) return false ; for ( let i = 2 ; i * i * i <= n ; i ++ ) if ( n % ( i * i * i ) == 0 ) return false ; return true ; } function prletCubeFree ( n ) { for ( let i = 2 ; i <= n ; i ++ ) { if ( isCubeFree ( i ) ) { document . write ( i + " " ) ; } } } let N = 20 ; prletCubeFree ( N ) ;
Decimal Equivalent of Gray Code and its Inverse | Function to convert given decimal number of gray code into its inverse in decimal form ; Taking xor until n becomes zero ; Driver Code
function inversegrayCode ( n ) { let inv = 0 ; for ( ; n ; n = n >> 1 ) inv ^= n ; return inv ; } let n = 15 ; document . write ( inversegrayCode ( n ) ) ;
Product of unique prime factors of a number | A function to print all prime factors of a given number n ; Handle prime factor 2 explicitly so that can optimally handle other prime factors . ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Driver Code
function productPrimeFactors ( n ) { var product = 1 ; if ( n % 2 == 0 ) { product *= 2 ; while ( n % 2 == 0 ) n = n / 2 ; } for ( i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { if ( n % i == 0 ) { product = product * i ; while ( n % i == 0 ) n = n / i ; } } if ( n > 2 ) product = product * n ; return product ; } var n = 44 ; document . write ( productPrimeFactors ( n ) ) ;
Maximizing Probability of one type from N containers | Returns the Maximum probability for Drawing 1 copy of number A from N containers with N copies each of numbers A and B ; Pmax = N / ( N + 1 ) ; Driver Code ; 1. N = 1 ; 2. N = 2 ; 3. N = 10
function calculateProbability ( N ) { let probability = N / ( N + 1 ) ; return probability ; } let N ; let probabilityMax ; N = 1 ; probabilityMax = calculateProbability ( N ) ; document . write ( " " + " " + N + " " + Math . round ( probabilityMax * 10000.0 ) / 10000.0 + " " ) ; N = 2 ; probabilityMax = calculateProbability ( N ) ; document . write ( " " + N + " " + Math . round ( probabilityMax * 10000.0 ) / 10000.0 + " " ) ; N = 10 ; probabilityMax = calculateProbability ( N ) ; document . write ( " " + N + " " + Math . round ( probabilityMax * 10000.0 ) / 10000.0 + " " ) ;
Program to implement standard deviation of grouped data | Function to find mean of grouped data . ; Function to find standard deviation of grouped data . ; Formula to find standard deviation deviation of grouped data . ; Declare and initialize the lower limit of interval . ; Declare and initialize the upper limit of interval . ; Calculating the size of array .
function mean ( mid , freq , n ) { let sum = 0 , freqSum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { sum = sum + mid [ i ] * freq [ i ] ; freqSum = freqSum + freq [ i ] ; } return sum / freqSum ; } function groupedSD ( lower_limit , upper_limit , freq , n ) { let mid = [ ] ; let sum = 0 , freqSum = 0 , sd ; for ( let i = 0 ; i < n ; i ++ ) { mid [ i ] = ( lower_limit [ i ] + upper_limit [ i ] ) / 2 ; sum = sum + freq [ i ] * mid [ i ] * mid [ i ] ; freqSum = freqSum + freq [ i ] ; } sd = Math . sqrt ( ( sum - freqSum * mean ( mid , freq , n ) * mean ( mid , freq , n ) ) / ( freqSum - 1 ) ) ; return sd ; } let lower_limit = [ 50 , 61 , 71 , 86 , 96 ] ; let upper_limit = [ 60 , 70 , 85 , 95 , 100 ] ; let freq = [ 9 , 7 , 9 , 12 , 8 ] ; let n = lower_limit . length ; document . write ( groupedSD ( lower_limit , upper_limit , freq , n ) ) ;
Average of first n even natural numbers | function to find average of sum of first n even numbers ; sum of first n even numbers ; calculating Average ; Driver Code
function avg_of_even_num ( n ) { let sum = 0 ; for ( let i = 1 ; i <= n ; i ++ ) sum += 2 * i ; return sum / n ; } let n = 9 ; document . write ( avg_of_even_num ( n ) ) ;
Average of first n even natural numbers | Return the average of sum of first n even numbers ; driver code
function avg_of_even_num ( n ) { return n + 1 ; } var n = 8 ; document . write ( avg_of_even_num ( n ) ) ;
Sum of square of first n odd numbers | JavaScript program to find sum of square of first n odd numbers . ; Driver code
function squareSum ( n ) { return n * ( 4 * n * n - 1 ) / 3 ; } document . write ( squareSum ( 8 ) ) ;
Check whether given three numbers are adjacent primes | Function checks whether given number is prime or not . ; check if n is a multiple of 2 ; if not , then just check the odds ; return next prime number ; start with next number . ; breaks after finding next prime number ; check given three numbers are adjacent primes are not . ; check given three numbers are primes are not . ; find next prime of a ; If next is not same as ' a ' ; If next next is not same as ' c ' ; Driver code
function isPrime ( n ) { if ( n % 2 == 0 ) return false ; for ( let i = 3 ; i * i <= n ; i += 2 ) if ( n % i == 0 ) return false ; return true ; } function nextPrime ( start ) { let next = start + 1 ; while ( ! isPrime ( next ) ) next ++ ; return next ; } function areAdjacentPrimes ( a , b , c ) { if ( ! isPrime ( a ) || ! isPrime ( b ) || ! isPrime ( c ) ) return false ; let next = nextPrime ( a ) ; if ( next != b ) return false ; if ( nextPrime ( b ) != c ) return false ; return true ; } if ( areAdjacentPrimes ( 11 , 13 , 19 ) ) document . write ( " " ) ; else document . write ( " " ) ;
Check whether a number is semiprime or not | Utility function to check whether number is semiprime or not ; If number is greater than 1 , add it to the count variable as it indicates the number remain is prime number ; Return '1' if count is equal to '2' else return '0' ; Function to print ' True ' or ' False ' according to condition of semiprime ; Driver code
function checkSemiprime ( num ) { let cnt = 0 ; for ( let i = 2 ; cnt < 2 && i * i <= num ; ++ i ) while ( num % i == 0 ) { num /= i ; ++ cnt ; } if ( num > 1 ) ++ cnt ; return cnt == 2 ? 1 : 0 ; } function semiprime ( n ) { if ( checkSemiprime ( n ) != 0 ) document . write ( " " + " " ) ; else document . write ( " " + " " ) ; } let n = 6 ; semiprime ( n ) ; n = 8 ; semiprime ( n ) ;
Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n | Function that find sum of series . ; Driver Code ; Function call
function sumOfSeries ( n ) { var sum = 0 ; for ( let i = 1 ; i <= n ; i ++ ) sum = sum + i * i ; return sum ; } var n = 10 ; document . write ( sumOfSeries ( n ) ) ;
Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n | Function that find sum of series . ; Driver Code
function sumOfSeries ( n ) { return ( n * ( n + 1 ) * ( 2 * n + 1 ) ) / 6 ; } var n = 10 ; document . write ( sumOfSeries ( n ) ) ;
Maximum binomial coefficient term value | Returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Return maximum binomial coefficient term value . ; If n is even ; If n is odd ; Driver Code
function binomialCoeff ( n , k ) { let C = new Array ( n + 1 ) ; for ( let i = 0 ; i <= n ; i ++ ) { C [ i ] = new Array ( k + 1 ) ; } for ( let i = 0 ; i <= n ; i ++ ) { for ( let j = 0 ; j <= Math . min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } function maxcoefficientvalue ( n ) { if ( n % 2 == 0 ) return binomialCoeff ( n , n / 2 ) ; else return binomialCoeff ( n , ( n + 1 ) / 2 ) ; } let n = 4 ; document . write ( maxcoefficientvalue ( n ) ) ;
Smallest n digit number divisible by given three numbers |  ; LCM for x , y , z ; returns smallest n digit number divisible by x , y and z ; find the LCM ; find power of 10 for least number ; reminder after ; If smallest number itself divides lcm . ; add lcm - reminder number for next n digit number ; this condition check the n digit number is possible or not if it is possible it return the number else return 0 ; Driver Code ; if number is possible then it print the number
function __gcd ( a , b ) { if ( b == 0 ) { return a ; } else { return __gcd ( b , a % b ) ; } } function LCM ( x , y , z ) { let ans = ( ( x * y ) / ( __gcd ( x , y ) ) ) ; return ( ( z * ans ) / ( __gcd ( ans , z ) ) ) ; } function findDivisible ( n , x , y , z ) { let lcm = LCM ( x , y , z ) ; let ndigitnumber = Math . pow ( 10 , n - 1 ) ; let reminder = ndigitnumber % lcm ; if ( reminder == 0 ) return ndigitnumber ; ndigitnumber += lcm - reminder ; if ( ndigitnumber < Math . pow ( 10 , n ) ) return ndigitnumber ; else return 0 ; } let n = 4 , x = 2 , y = 3 , z = 5 ; let res = findDivisible ( n , x , y , z ) ; if ( res != 0 ) document . write ( res ) ; else document . write ( " " ) ;
Sum of squares of first n natural numbers | Return the sum of square of first n natural numbers ; Driven Program
function squaresum ( n ) { return ( n * ( n + 1 ) / 2 ) * ( 2 * n + 1 ) / 3 ; } let n = 4 ; document . write ( squaresum ( n ) ) ;
Program to calculate distance between two points | Function to calculate distance ; Calculating distance ; Drivers Code
function distance ( x1 , y1 , x2 , y2 ) { return Math . sqrt ( Math . pow ( x2 - x1 , 2 ) + Math . pow ( y2 - y1 , 2 ) * 1.0 ) ; } document . write ( distance ( 3 , 4 , 4 , 3 ) ) ;
Check if a large number is divisibility by 15 | to find sum ; function to check if a large number is divisible by 15 ; length of string ; check divisibility by 5 ; Sum of digits ; if divisible by 3 ; Driver Code
function accumulate ( s ) { let acc = 0 ; for ( let i = 0 ; i < s . length ; i ++ ) { acc += s [ i ] - ' ' ; } return acc ; } function isDivisible ( s ) { let n = s . length ; if ( s [ n - 1 ] != ' ' && s [ n - 1 ] != ' ' ) return false ; let sum = accumulate ( s ) ; return ( sum % 3 == 0 ) ; } let s = " " ; isDivisible ( s ) ? document . write ( " " ) : document . write ( " " ) ; s = " " ; isDivisible ( s ) ? document . write ( " " ) : document . write ( " " ) ;
Frequency of maximum occurring subsequence in given string | Function to find the frequency ; freq stores frequency of each english lowercase character ; dp [ i ] [ j ] stores the count of subsequence with ' a ' + i and ' a ' + j character ; Increment the count of subsequence j and s [ i ] ; Update the frequency array ; For 1 length subsequence ; For 2 length subsequence ; Return the final result ; Given string str ; Function Call
function findCount ( s ) { var freq = Array ( 26 ) . fill ( 0 ) ; var dp = Array . from ( Array ( 26 ) , ( ) => Array ( 26 ) . fill ( 0 ) ) ; for ( var i = 0 ; i < s . length ; ++ i ) { for ( var j = 0 ; j < 26 ; j ++ ) { dp [ j ] [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] += freq [ j ] ; } freq [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } var ans = 0 ; for ( var i = 0 ; i < 26 ; i ++ ) ans = Math . max ( freq [ i ] , ans ) ; for ( var i = 0 ; i < 26 ; i ++ ) { for ( var j = 0 ; j < 26 ; j ++ ) { ans = Math . max ( dp [ i ] [ j ] , ans ) ; } } return ans ; } var str = " " ; document . write ( findCount ( str ) ) ;
Create an array such that XOR of subarrays of length K is X | Function to construct the array ; Creating a vector of size K , initialised with 0 ; Initialising the first element with the given XOR ; Driver code
function constructArray ( N , K , X ) { let ans = new Array ( K ) . fill ( 0 ) ; ans [ 0 ] = X ; for ( let i = 0 ; i < N ; ++ i ) { document . write ( ans [ i % K ] + " " ) ; } document . write ( " " ) ; } let N = 5 , K = 2 , X = 4 ; constructArray ( N , K , X ) ;
Two player game in which a player can remove all occurrences of a number | Function that print whether player1 can wins or loses ; Storing the number of occurrence of elements in unordered map ; variable to check if the occurrence of repeated elements is >= 4 and multiple of 2 or not ; count elements which occur more than once ; Driver code
function game ( v , n ) { let m = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( ! m . has ( v [ i ] ) ) m . set ( v [ i ] , 1 ) ; else m . set ( v [ i ] , m . get ( v [ i ] ) + 1 ) ; } let count = 0 ; let check = 0 ; for ( let [ key , value ] of m . entries ( ) ) { if ( value > 1 ) { if ( value >= 4 && value % 2 == 0 ) check ++ ; count ++ ; } } let flag ; if ( check % 2 != 0 ) flag = false ; if ( check % 2 != 0 ) document . write ( " " ) ; else if ( n % 2 == 0 && count % 2 == 0 ) document . write ( " " ) ; else document . write ( " " ) ; } let arr = [ 3 , 2 , 2 , 3 , 3 , 5 ] ; let size = arr . length ; game ( arr , size ) ;
Count of elements which form a loop in an Array according to given constraints | Function to count number of elements forming a cycle ; Array to store parent node of traversal . ; Array to determine whether current node is already counted in the cycle . ; Initialize the arrays . ; Check if current node is already traversed or not . If node is not traversed yet then parent value will be - 1. ; Traverse the graph until an already visited node is not found . ; Check parent value to ensure a cycle is present . ; Count number of nodes in the cycle . ; Driver code
function solve ( A , n ) { let i , cnt = 0 , j ; let parent = new Array ( n ) ; let vis = new Array ( n ) ; parent . fill ( - 1 ) ; vis . fill ( 0 ) ; for ( i = 0 ; i < n ; i ++ ) { j = i ; if ( parent [ j ] == - 1 ) { while ( parent [ j ] == - 1 ) { parent [ j ] = i ; j = __gcd ( j , A [ j ] ) % n ; } if ( parent [ j ] == i ) { while ( vis [ j ] == 0 ) { vis [ j ] = 1 ; cnt ++ ; j = __gcd ( j , A [ j ] ) % n ; } } } } return cnt ; } function __gcd ( a , b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } let A = [ 1 , 1 , 6 , 2 ] ; let n = A . length ; document . write ( solve ( A , n ) ) ;
Find farthest node from each node in Tree | Javascript implementation to find the farthest node from each vertex of the tree ; Adjacency list to store edges ; Add edge between U and V in tree ; Edge from U to V ; Edge from V to U ; DFS to find the first End Node of diameter ; Calculating level of nodes ; Go in opposite direction of parent ; Function to clear the levels of the nodes ; Set all value of lvl [ ] to 0 for next dfs ; Set maximum with 0 ; DFS will calculate second end of the diameter ; Calculating level of nodes ; Store the node with maximum depth from end1 ; Go in opposite direction of parent ; Function to find the distance of the farthest distant node ; Storing distance from end1 to node u ; Function to find the distance of nodes from second end of diameter ; Storing distance from end2 to node u ; Joining Edge between two nodes of the tree ; Find the one end of the diameter of tree ; Find the other end of the diameter of tree ; Find the distance to each node from end1 ; Find the distance to each node from end2 ; Comparing distance between the two ends of diameter ; Driver Code ; Function call
let N = 10000 ; let adj = new Array ( N ) ; let lvl = new Array ( N ) ; let dist1 = new Array ( N ) ; let dist2 = new Array ( N ) ; let end = 0 , end2 = 0 , maxi = 0 ; for ( let i = 0 ; i < N ; i ++ ) { lvl [ i ] = 0 ; dist1 [ i ] = - 1 ; dist2 [ i ] = - 1 ; } function AddEdge ( u , v ) { adj [ u ] . push ( v ) ; adj [ v ] . push ( u ) ; } function findFirstEnd ( u , p ) { lvl [ u ] = 1 + lvl [ p ] ; if ( lvl [ u ] > maxi ) { maxi = lvl [ u ] ; end1 = u ; } for ( let i = 0 ; i < adj [ u ] . length ; i ++ ) { if ( adj [ u ] [ i ] != p ) { findFirstEnd ( adj [ u ] [ i ] , u ) ; } } } function clear ( n ) { for ( let i = 0 ; i <= n ; i ++ ) { lvl [ i ] = 0 ; } maxi = 0 ; dist1 [ 0 ] = dist2 [ 0 ] = - 1 ; } function findSecondEnd ( u , p ) { lvl [ u ] = 1 + lvl [ p ] ; if ( lvl [ u ] > maxi ) { maxi = lvl [ u ] ; end2 = u ; } for ( let i = 0 ; i < adj [ u ] . length ; i ++ ) { if ( adj [ u ] [ i ] != p ) { findSecondEnd ( adj [ u ] [ i ] , u ) ; } } } function findDistancefromFirst ( u , p ) { dist1 [ u ] = 1 + dist1 [ p ] ; for ( let i = 0 ; i < adj [ u ] . length ; i ++ ) { if ( adj [ u ] [ i ] != p ) { findDistancefromFirst ( adj [ u ] [ i ] , u ) ; } } } function findDistancefromSecond ( u , p ) { dist2 [ u ] = 1 + dist2 [ p ] ; for ( let i = 0 ; i < adj [ u ] . length ; i ++ ) { if ( adj [ u ] [ i ] != p ) { findDistancefromSecond ( adj [ u ] [ i ] , u ) ; } } } function findNodes ( ) { let n = 5 ; AddEdge ( 1 , 2 ) ; AddEdge ( 1 , 3 ) ; AddEdge ( 3 , 4 ) ; AddEdge ( 3 , 5 ) ; findFirstEnd ( 1 , 0 ) ; clear ( n ) ; findSecondEnd ( end1 , 0 ) ; findDistancefromFirst ( end1 , 0 ) ; findDistancefromSecond ( end2 , 0 ) ; for ( let i = 1 ; i <= n ; i ++ ) { let x = dist1 [ i ] ; let y = dist2 [ i ] ; if ( x >= y ) { document . write ( end1 + " " ) ; } else { document . write ( end2 + " " ) ; } } } for ( let i = 0 ; i < N ; i ++ ) { adj [ i ] = [ ] ; } findNodes ( ) ;
Sum and Product of all even digit sum Nodes of a Singly Linked List | Node of Linked List ; Function to insert a node at the beginning of the singly Linked List ; Allocate new node ; Insert the data ; Link old list to the new node ; Move head to povar the new node ; Function to find the digit sum for a number ; Return the sum ; Function to find the required sum and product ; Initialise the sum and product to 0 and 1 respectively ; Traverse the given linked list ; If current node has even digit sum then include it in resultant sum and product ; Find the sum and the product ; Prvar the final Sum and Product ; Head of the linked list ; Create the linked list 15.16 . 8.6 .13 ; Function call
class Node { constructor ( val ) { this . data = val ; this . next = null ; } } function push ( head_ref , new_data ) { var new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } function digitSum ( num ) { var sum = 0 ; while ( num > 0 ) { sum += ( num % 10 ) ; num = parseInt ( num / 10 ) ; } return sum ; } function sumAndProduct ( head_ref ) { var prod = 1 ; var sum = 0 ; var ptr = head_ref ; while ( ptr != null ) { if ( ( digitSum ( ptr . data ) % 2 != 1 ) ) { prod *= ptr . data ; sum += ptr . data ; } ptr = ptr . next ; } document . write ( " " + sum + " " ) ; document . write ( " " + prod ) ; } var head = null ; head = push ( head , 13 ) ; head = push ( head , 6 ) ; head = push ( head , 8 ) ; head = push ( head , 16 ) ; head = push ( head , 15 ) ; sumAndProduct ( head ) ;
Shortest Palindromic Substring | Function return the shortest palindromic substring ; One by one consider every character as center point of even and length palindromes ; Find the longest odd length palindrome with center point as i ; Find the even length palindrome with center points as i - 1 and i . ; Smallest substring which is not empty ; Driver code
function ShortestPalindrome ( s ) { let n = s . length ; let v = [ ] ; for ( let i = 0 ; i < n ; i ++ ) { let l = i ; let r = i ; let ans1 = " " ; let ans2 = " " ; while ( l >= 0 && r < n && s [ l ] == s [ r ] ) { ans1 += s [ l ] ; l -- ; r ++ ; } l = i - 1 ; r = i ; while ( l >= 0 && r < n && s [ l ] == s [ r ] ) { ans2 += s [ l ] ; l -- ; r ++ ; } v . push ( ans1 ) ; v . push ( ans2 ) ; } let ans = v [ 0 ] ; for ( let i = 0 ; i < v . length ; i ++ ) { if ( v [ i ] != " " ) { if ( ans [ 0 ] >= v [ i ] [ 0 ] ) { ans = v [ i ] ; } } } return ans ; } let s = " " ; document . write ( ShortestPalindrome ( s ) ) ;
Minimum increment or decrement operations required to make the array sorted | Function to return the minimum number of given operations required to sort the array ; Number of elements in the array ; Smallest element in the array ; Largest element in the array ; dp ( i , j ) represents the minimum number of operations needed to make the array [ 0 . . i ] sorted in non - decreasing order given that ith element is j ; Fill the dp [ ] ] [ array for base cases ; Using results for the first ( i - 1 ) elements , calculate the result for the ith element ; If the ith element is j then we can have any value from small to j for the i - 1 th element We choose the one that requires the minimum operations ; If we made the ( n - 1 ) th element equal to j we required dp ( n - 1 , j ) operations We choose the minimum among all possible dp ( n - 1 , j ) where j goes from small to large ; Driver code
function getMinimumOps ( ar ) { var n = ar . length ; var small = Math . min . apply ( Math , ar ) ; var large = Math . max . apply ( Math , ar ) ; var dp = new Array ( n ) ; var i , j ; for ( i = 0 ; i < dp . length ; i ++ ) dp [ i ] = new Array ( large + 1 ) ; for ( j = small ; j <= large ; j ++ ) { dp [ 0 ] [ j ] = Math . abs ( ar [ 0 ] - j ) ; } for ( i = 1 ; i < n ; i ++ ) { var minimum = 2147483647 ; for ( j = small ; j <= large ; j ++ ) { minimum = Math . min ( minimum , dp [ i - 1 ] [ j ] ) ; dp [ i ] [ j ] = minimum + Math . abs ( ar [ i ] - j ) ; } } var ans = 2147483647 ; for ( j = small ; j <= large ; j ++ ) { ans = Math . min ( ans , dp [ n - 1 ] [ j ] ) ; } return ans ; } var ar = [ 1 , 2 , 1 , 4 , 3 ] ; document . write ( getMinimumOps ( ar ) ) ;
Minimize the cost of partitioning an array into K groups | Function to return the minimum number of operations needed to partition the array in k contiguous groups such that all elements of a given group are identical ; n is the size of the array ; dp ( i , j ) represents the minimum cost for partitioning the array [ 0. . i ] into j groups ; Base case , cost is 0 for parititoning the array [ 0. .0 ] into 1 group ; Fill dp ( i , j ) and the answer will be stored at dp ( n - 1 , k ) ; The maximum groups that the segment 0. . i can be divided in is represented by maxGroups ; Initialize dp ( i , j ) to infinity ; Divide segment 0. . i in 1 group ; map and freqOfMode are together used to keep track of the frequency of the most occurring element in [ 0. . i ] ; Change all the elements in the range 0. . i to the most frequent element in this range ; If the jth group is the segment from it . . i , we change all the elements in this range to this range 's most occurring element ; Number of elements we need to change in the jth group i . e . the range it . . i ; For all the possible sizes of the jth group that end at the ith element we pick the size that gives us the minimum cost for dp ( i , j ) elementsToChange is the cost of making all the elements in the jth group identical and we make use of dp ( it - 1 , j - 1 ) to find the overall minimal cost ; Return the minimum cost for partitioning array [ 0. . n - 1 ] into k groups which is stored at dp ( n - 1 , k ) ; Driver code
function getMinimumOps ( ar , k ) { let n = ar . length ; let dp = new Array ( n ) ; for ( let i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( k + 1 ) ; for ( let j = 0 ; j < ( k + 1 ) ; j ++ ) { dp [ i ] [ j ] = 0 ; } } dp [ 0 ] [ 1 ] = 0 ; for ( let i = 1 ; i < n ; i ++ ) { let maxGroups = Math . min ( k , i + 1 ) ; for ( let j = 1 ; j <= maxGroups ; j ++ ) { dp [ i ] [ j ] = Number . MAX_VALUE ; if ( j == 1 ) { let freq = new Array ( 100000 ) ; for ( let i = 0 ; i < freq . length ; i ++ ) { freq [ i ] = 0 ; } let freqOfMode = 0 ; for ( let it = 0 ; it <= i ; it ++ ) { freq [ ar [ it ] ] ++ ; let newElementFreq = freq [ ar [ it ] ] ; if ( newElementFreq > freqOfMode ) freqOfMode = newElementFreq ; } dp [ i ] [ 1 ] = ( i + 1 ) - freqOfMode ; } else { let freq = new Array ( 100000 ) ; for ( let i = 0 ; i < freq . length ; i ++ ) { freq [ i ] = 0 ; } let freqOfMode = 0 ; for ( let it = i ; it >= j - 1 ; it -- ) { freq [ ar [ it ] ] ++ ; let newElementFreq = freq [ ar [ it ] ] ; if ( newElementFreq > freqOfMode ) freqOfMode = newElementFreq ; let elementsToChange = i - it + 1 ; elementsToChange -= freqOfMode ; dp [ i ] [ j ] = Math . min ( dp [ it - 1 ] [ j - 1 ] + elementsToChange , dp [ i ] [ j ] ) ; } } } } return dp [ n - 1 ] [ k ] ; } let k = 3 ; let ar = [ 3 , 1 , 3 , 3 , 2 , 1 , 8 , 5 ] ; document . write ( getMinimumOps ( ar , k ) ) ;