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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem