Count of arrays having consecutive element with different values
Last Updated :
13 Sep, 2023
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 109
using namespace std;
// Return the number of arrays with given constraints.
int countarray(int n, int k, int x)
{
int dp[MAXN] = { 0 };
// Initialising dp[0] and dp[1].
dp[0] = 0;
dp[1] = 1;
// Computing f(i) for each 2 <= i <= n.
for (int 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 Program
int main()
{
int n = 4, k = 3, x = 2;
cout << countarray(n, k, x) << endl;
return 0;
}
Java
// Java program to find count of arrays.
import java.util.*;
class Counting
{
static int MAXN = 109;
public static int countarray(int n, int k,
int x)
{
int[] dp = new int[109];
// Initialising dp[0] and dp[1].
dp[0] = 0;
dp[1] = 1;
// Computing f(i) for each 2 <= i <= n.
for (int 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 code
public static void main(String[] args)
{
int n = 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.
def countarray( 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
while i < n:
dp.append( (k - 2) * dp[i - 1] +
(k - 1) * dp[i - 2])
i = i + 1
return ( (k - 1) * dp[n - 2] if x == 1 else dp[n - 1])
# Driven code
n = 4
k = 3
x = 2
print(countarray(n, k, x))
# This code is contributed by "Sharad_Bhardwaj".
C#
// C# program to find count of arrays.
using System;
class GFG
{
// static int MAXN = 109;
public static int countarray(int n, int k,
int x)
{
int[] dp = new int[109];
// Initialising dp[0] and dp[1].
dp[0] = 0;
dp[1] = 1;
// Computing f(i) for each 2 <= i <= n.
for (int 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 code
public static void Main()
{
int n = 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;
function countarray(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 code
let 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.
function countarray($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;
echo countarray($n, $k, $x) ;
// This code is contributed by anuj_67.
?>
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 109
using namespace std;
// Return the number of arrays with given constraints.
int countarray(int n, int k, int x)
{
// initialize variables to store previous values
int prev1 = 0, prev2 = 1, curr;
// Computing f(i) for each 2 <= i <= n.
for (int i = 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
int main()
{
int n = 4, k = 3, x = 2;
// function call
cout << countarray(n, k, x) << endl;
return 0;
}
Java
import java.util.*;
public class Main {
// Return the number of arrays with given constants.
static int countArray(int n, int k, int x)
{
// initialize variables to store previous values
int prev1 = 0, prev2 = 1, curr;
// Computing f(i) for each 2 <= i <= n.
for (int i = 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
public static void main(String[] args)
{
int n = 4, k = 3, x = 2;
// function call
System.out.println(countArray(n, k, x));
}
}
Python3
def countarray(n, k, x):
# initialize variables to store previous values
prev1 = 0
prev2 = 1
# Computing f(i) for each 2 <= i <= n.
for i in range(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 if x == 1 else prev2
# Driven Program
n = 4
k = 3
x = 2
# function call
print(countarray(n, k, x))
C#
using System;
public class Program
{
// Return the number of arrays with given constartints.
public static int CountArray(int n, int k, int x)
{
// initialize variables to store previous values
int prev1 = 0, prev2 = 1, curr;
// Computing f(i) for each 2 <= i <= n.
for (int i = 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
public static void Main()
{
int n = 4, k = 3, x = 2;
// function call
Console.WriteLine(CountArray(n, k, x));
}
}
JavaScript
// Function to calculate the number of arrays with given constants.
function countArray(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 values
let n = 4, k = 3, x = 2;
// Calculate and output the result
console.log(countArray(n, k, x));
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Count Subarrays with Consecutive elements differing by 1
Given an array arr[] of N integers. The task is to count the total number of subarrays of the given array such that the difference between the consecutive elements in the subarrays is one. That is, for any index i in the subarrays, arr[i+1] - arr[i] = 1. Note: Do not consider subarrays with a single
12 min read
Count of all subsequences having adjacent elements with different parity
Given an array arr[] of size N, the task is to find the number of non-empty subsequences from the given array such that no two adjacent elements of the subsequence have the same parity. Examples: Input: arr[] = [5, 6, 9, 7] Output: 9 Explanation: All such subsequences of given array will be {5}, {6}
9 min read
Count ways to generate an array having distinct elements at M consecutive indices
Given an array arr[] consisting of N integers in the range [0, M] and an integer M, the task is to count the number of ways to replace all array elements whose value is 0 with non-zero values from the range [0, M] such that all possible M consecutive elements are distinct. Examples: Input: arr[] = {
10 min read
Count Subarrays with strictly decreasing consecutive elements
Given an array arr[] containing integers. The task is to find the number of decreasing subarrays with a difference of 1. Examples: Input: arr[] = {3, 2, 1, 4}Output: 7Explanation: Following are the possible decreasing subarrays with difference 1. [3], [2], [1], [4], [3,2], [2,1], and [3,2,1]Therefor
7 min read
Construct an Array having K Subarrays with all distinct elements
Given integers N and K, the task is to construct an array arr[] of size N using numbers in the range [1, N] such that it has K sub-arrays whose all the elements are distinct. Note: If there are multiple possible answers return any of them. Examples: Input: N = 5, K = 8Output: {1, 2, 3, 3, 3}Explanat
7 min read
Count of pairs containing even or consecutive elements from given Array
Given an array arr[] of even size, the task is to find the count of pairs after partitioning arr[] into pairs, such that: each element of arr[] belongs to exactly one pairboth of them are even orabsolute difference between them is 1, i.e, |X - Y| = 1. Examples: Input: arr[] = {11, 12, 16, 14}Output:
12 min read
Count of non decreasing Arrays with ith element in range [A[i], B[i]]
Given two arrays A[] and B[] both consisting of N integers, the task is to find the number of non-decreasing arrays of size N that can be formed such that each array element lies over the range [A[i], B[i]]. Examples: Input: A[] = {1, 1}, B[] = {2, 3}Output: 5Explanation:The total number of valid ar
9 min read
Count subarrays having total distinct elements same as original array
Given an array of n integers. Count the total number of sub-arrays having total distinct elements, the same as that of the total distinct elements of the original array. Examples: Input : arr[] = {2, 1, 3, 2, 3} Output : 5 Total distinct elements in array is 3 Total sub-arrays that satisfy the condi
11 min read
Count consecutive pairs of same elements
Given an array arr[], the task is to count the number of pairs formed by consecutive elements in which both of the elements in a pair are same.Examples: Input: arr[] = {1, 2, 2, 3, 4, 4, 5, 5, 5, 5} Output: 5 (1, 2), (4, 5), (6, 7), (7, 8) and (8, 9) are the valid index pairs where consecutive eleme
4 min read
Replacing an element makes array elements consecutive
Given an array of positive distinct integers. We need to find the only element whose replacement with any other value makes array elements distinct consecutive. If it is not possible to make array elements consecutive, return -1. Examples : Input : arr[] = {45, 42, 46, 48, 47} Output : 42 Explanatio
8 min read