Count of arrays having consecutive element with different values

Given three positive integers n, k and x. The task is to count the number of different array that can be formed of size n such that each element is between 1 to k and two consecutive element are different. Also, the first and last elements of each array should be 1 and x respectively.
Examples :
Input : n = 4, k = 3, x = 2
Output : 3
The idea is to use Dynamic Programming and combinatorics to solve the problem. 
First of all, notice that the answer is same for all x from 2 to k. It can easily be proved. This will be useful later on. 
Let the state f(i) denote the number of ways to fill the range [1, i] of array A such that A1 = 1 and Ai ? 1. 
Therefore, if x ? 1, the answer to the problem is f(n)/(k – 1), because f(n) is the number of way where An is filled with a number from 2 to k, and the answer are equal for all such values An, so the answer for an individual value is f(n)/(k – 1). 
Otherwise, if x = 1, the answer is f(n – 1), because An – 1 ? 1, and the only number we can fill An with is x = 1. 
Now, the main problem is how to calculate f(i). Consider all numbers that Ai – 1 can be. We know that it must lie in [1, k].
- If Ai – 1 ? 1, then there are (k – 2)f(i – 1) ways to fill in the rest of the array, because Ai cannot be 1 or Ai – 1 (so we multiply with (k – 2)), and for the range [1, i – 1], there are, recursively, f(i – 1) ways.
- If Ai – 1 = 1, then there are (k – 1)f(i – 2) ways to fill in the rest of the array, because Ai – 1 = 1 means Ai – 2 ? 1 which means there are f(i – 2)ways to fill in the range [1, i – 2] and the only value that Ai cannot be 1, so we have (k – 1) choices for Ai.
By combining the above, we get
f(i) = (k - 1) * f(i - 2) + (k - 2) * f(i - 1)
This will help us to use dynamic programming using f(i).
Below is the implementation of this approach:
C++
| // CPP Program to find count of arrays.#include <bits/stdc++.h>#define MAXN 109usingnamespacestd;// Return the number of arrays with given constraints.intcountarray(intn, intk, intx){    intdp[MAXN] = { 0 };    // Initialising dp[0] and dp[1].    dp[0] = 0;    dp[1] = 1;    // Computing f(i) for each 2 <= i <= n.    for(inti = 2; i < n; i++)        dp[i] = (k - 2) * dp[i - 1] +                (k - 1) * dp[i - 2];    return(x == 1 ? (k - 1) * dp[n - 2] : dp[n - 1]);}// Driven Programintmain(){    intn = 4, k = 3, x = 2;    cout << countarray(n, k, x) << endl;    return0;} | 
Java
| // Java program to find count of arrays.importjava.util.*;classCounting{    staticintMAXN = 109;    publicstaticintcountarray(intn, intk,                                        intx)    {        int[] dp = newint[109];        // Initialising dp[0] and dp[1].        dp[0] = 0;        dp[1] = 1;        // Computing f(i) for each 2 <= i <= n.        for(inti = 2; i < n; i++)            dp[i] = (k - 2) * dp[i - 1] +                (k - 1) * dp[i - 2];        return(x == 1? (k - 1) * dp[n - 2] :                                   dp[n - 1]);    }        // driver code    publicstaticvoidmain(String[] args)    {        intn = 4, k = 3, x = 2;        System.out.println(countarray(n, k, x));    }}// This code is contributed by rishabh_jain | 
Python3
| # Python3 code to find count of arrays.# Return the number of lists with # given constraints.defcountarray( n , k , x ):        dp =list()        # Initialising dp[0] and dp[1]    dp.append(0)    dp.append(1)        # Computing f(i) for each 2 <= i <= n.    i =2    whilei < n:        dp.append( (k -2) *dp[i -1] +                   (k -1) *dp[i -2])        i =i +1        return( (k -1) *dp[n -2] ifx ==1elsedp[n -1])# Driven coden =4k =3x =2print(countarray(n, k, x))# This code is contributed by "Sharad_Bhardwaj". | 
C#
| // C# program to find count of arrays.usingSystem;classGFG{// static int MAXN = 109;    publicstaticintcountarray(intn, intk,                                     intx)    {        int[] dp = newint[109];        // Initialising dp[0] and dp[1].        dp[0] = 0;        dp[1] = 1;        // Computing f(i) for each 2 <= i <= n.        for(inti = 2; i < n; i++)            dp[i] = (k - 2) * dp[i - 1] +                    (k - 1) * dp[i - 2];        return(x == 1 ? (k - 1) * dp[n - 2] :                                    dp[n - 1]);    }        // Driver code    publicstaticvoidMain()    {        intn = 4, k = 3, x = 2;        Console.WriteLine(countarray(n, k, x));    }}// This code is contributed by vt_m | 
Javascript
| <script>// Javascript program to find count of arrays.let MAXN = 109;  functioncountarray(n, k, x){    let dp = [];    // Initialising dp[0] and dp[1].    dp[0] = 0;    dp[1] = 1;    // Computing f(i) for each 2 <= i <= n.    for(let i = 2; i < n; i++)        dp[i] = (k - 2) * dp[i - 1] +                (k - 1) * dp[i - 2];    return(x == 1 ? (k - 1) * dp[n - 2] :                                dp[n - 1]);}// Driver codelet n = 4, k = 3, x = 2;document.write(countarray(n, k, x));// This code is contributed by sanjoy_62</script> | 
PHP
| <?php// PHP Program to find // count of arrays.$MAXN= 109;// Return the number of arrays// with given constraints.functioncountarray($n, $k, $x){    $dp= array( 0 );    // Initialising dp[0] and dp[1].    $dp[0] = 0;    $dp[1] = 1;    // Computing f(i) for     // each 2 <= i <= n.    for( $i= 2; $i< $n; $i++)        $dp[$i] = ($k- 2) * $dp[$i- 1] +                  ($k- 1) * $dp[$i- 2];    return($x== 1 ? ($k- 1) *             $dp[$n- 2] : $dp[$n- 1]);}// Driven Code$n= 4; $k= 3; $x= 2;echocountarray($n, $k, $x) ;// This code is contributed by anuj_67.?> | 
3
Time Complexity: O(n)
Auxiliary Space: O(MAXN), here MAXN = 109
Efficient approach: Space optimization O(1)
In the approach we have only used three variables , prev1 and prev2 to store the values of the previous two elements of the dp array and curr to store the current value. Therefore, the space complexity of the optimized code is O(1)
Implementation Steps:
- Create 2 variables prev1 and prev2 to keep track of the previous 2 values of DP and curr to store the current value.
- Initialize prev1 and prev2 with 0 and 1 as base cases.
- Now iterate through loop and get the current value form previous 2 values.
- after Every iteration assign prev2 to prev1 and curr to prev2 to iterate further;
- At last return answer.
Implementation:
C++
| // CPP Program to find count of arrays.#include <bits/stdc++.h>#define MAXN 109usingnamespacestd;// Return the number of arrays with given constraints.intcountarray(intn, intk, intx){    // initialize variables to store previous values    intprev1 = 0, prev2 = 1, curr;    // Computing f(i) for each 2 <= i <= n.    for(inti = 2; i < n; i++) {        curr = (k - 2) * prev2 + (k - 1) * prev1;        // assigning values to iterate further        prev1 = prev2;        prev2 = curr;    }    // return final answer    return(x == 1 ? (k - 1) * prev1 : prev2);}// Driven Programintmain(){    intn = 4, k = 3, x = 2;    // function call    cout << countarray(n, k, x) << endl;    return0;} | 
Java
| importjava.util.*;publicclassMain {    // Return the number of arrays with given constants.    staticintcountArray(intn, intk, intx)    {        // initialize variables to store previous values        intprev1 = 0, prev2 = 1, curr;        // Computing f(i) for each 2 <= i <= n.        for(inti = 2; i < n; i++) {            curr = (k - 2) * prev2 + (k - 1) * prev1;            // assigning values to iterate further            prev1 = prev2;            prev2 = curr;        }        // return final answer        return(x == 1? (k - 1) * prev1 : prev2);    }    // Driver Program    publicstaticvoidmain(String[] args)    {        intn = 4, k = 3, x = 2;        // function call        System.out.println(countArray(n, k, x));    }} | 
Python3
| defcountarray(n, k, x):    # initialize variables to store previous values    prev1 =0    prev2 =1    # Computing f(i) for each 2 <= i <= n.    fori inrange(2, n):        curr =(k -2) *prev2 +(k -1) *prev1        # assigning values to iterate further        prev1 =prev2        prev2 =curr    # return final answer    return(k -1) *prev1 ifx ==1elseprev2# Driven Programn =4k =3x =2# function callprint(countarray(n, k, x)) | 
C#
| usingSystem;publicclassProgram {  // Return the number of arrays with given constartints.  publicstaticintCountArray(intn, intk, intx)  {    // initialize variables to store previous values    intprev1 = 0, prev2 = 1, curr;    // Computing f(i) for each 2 <= i <= n.    for(inti = 2; i < n; i++) {      curr = (k - 2) * prev2 + (k - 1) * prev1;      // assigning values to iterate further      prev1 = prev2;      prev2 = curr;    }    // return final answer    return(x == 1 ? (k - 1) * prev1 : prev2);  }  // Driven Program  publicstaticvoidMain()  {    intn = 4, k = 3, x = 2;    // function call    Console.WriteLine(CountArray(n, k, x));  }} | 
Javascript
| // Function to calculate the number of arrays with given constants.functioncountArray(n, k, x) {    let prev1 = 0, prev2 = 1, curr;    // Computing f(i) for each 2 <= i < n.    for(let i = 2; i < n; i++) {        // Calculate the current value using the given formula.        curr = (k - 2) * prev2 + (k - 1) * prev1;                // Update the previous values for the next iteration.        prev1 = prev2;        prev2 = curr;    }        // Return the final answer based on the value of x.    return(x === 1 ? (k - 1) * prev1 : prev2);}// Input valueslet n = 4, k = 3, x = 2;// Calculate and output the resultconsole.log(countArray(n, k, x)); | 
3
Time Complexity: O(n)
Auxiliary Space: O(1) 
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
 
				 
					



