Count of Arrays of size N having absolute difference between adjacent elements at most 1
Last Updated :
07 Dec, 2023
Given a positive integer M and an array arr[] of size N and a few integers are missing in the array represented as -1, the task is to find the count of distinct arrays after replacing all -1 with the elements over the range [1, M] such that the absolute difference between any pair of adjacent elements is at most 1.
Examples:
Input: arr[] = {2, -1, 2}, M = 5
Output: 3
Explanation:
The arrays that follow the given conditions are {2, 1, 2}, {2, 2, 2} and {2, 3, 2}.
Input: arr[] = {4, -1, 2, 1, -1, -1}, M = 10
Output: 5
Recursive approach:
An approach to solve this problem would be to use recursion to generate all possible combinations of elements in the array, replacing the -1 entries with all possible values in the range [1, M] that satisfy the given conditions. To avoid generating duplicates, we can use a set to store the distinct arrays.
- The check() function checks whether an array arr of size N satisfies the given condition that the absolute difference between any adjacent elements is at most 1. The function iterates through the array and checks the absolute difference between each pair of adjacent elements. If the absolute difference is greater than 1 and both elements are not equal to -1, the function returns false. Otherwise, it returns true.
- The generate() function generates all possible arrays by replacing the -1 entries in arr with all possible values in the range [1, M] that satisfy the given conditions.
- The function works recursively by filling the pos-th entry of arr with all possible values in [1, M] and calling itself with pos+1 until all positions in arr are filled. If the resulting array satisfies the given condition, it is added to the set s to avoid duplicates.
- The countArray() function calls the generate() function and returns the size of the set s, which contains all distinct arrays that satisfy the given conditions.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool check( int arr[], int N) {
for ( int i = 1; i < N; i++) {
if (arr[i] != -1 && arr[i-1] != -1 && abs (arr[i] - arr[i-1]) > 1)
return false ;
}
return true ;
}
void generate( int arr[], int pos, int N, int M, set<vector< int >>& s) {
if (pos == N) {
if (check(arr, N))
s.insert(vector< int >(arr, arr+N));
return ;
}
if (arr[pos] != -1) {
generate(arr, pos+1, N, M, s);
} else {
for ( int i = 1; i <= M; i++) {
arr[pos] = i;
generate(arr, pos+1, N, M, s);
arr[pos] = -1;
}
}
}
int countArray( int arr[], int N, int M) {
set<vector< int >> s;
generate(arr, 0, N, M, s);
return s.size();
}
int main() {
int arr[] = { 4, -1, 2, 1, -1, -1 };
int N = sizeof (arr) / sizeof (arr[0]);
int M = 10;
cout << countArray(arr, N, M) << endl;
return 0;
}
|
Java
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;
import java.util.Arrays;
public class CountArrays {
static boolean check( int [] arr, int N) {
for ( int i = 1 ; i < N; i++) {
if (arr[i] != - 1 && arr[i - 1 ] != - 1 && Math.abs(arr[i] - arr[i - 1 ]) > 1 )
return false ;
}
return true ;
}
static void generate( int [] arr, int pos, int N, int M, Set<Vector<Integer>> s) {
if (pos == N) {
if (check(arr, N)) {
Vector<Integer> triplet = new Vector<>();
for ( int num : arr) {
triplet.add(num);
}
s.add(triplet);
}
return ;
}
if (arr[pos] != - 1 ) {
generate(arr, pos + 1 , N, M, s);
} else {
for ( int i = 1 ; i <= M; i++) {
arr[pos] = i;
generate(arr, pos + 1 , N, M, s);
arr[pos] = - 1 ;
}
}
}
static int countArray( int [] arr, int N, int M) {
Set<Vector<Integer>> s = new HashSet<>();
generate(arr, 0 , N, M, s);
return s.size();
}
public static void main(String[] args) {
int [] arr = { 4 , - 1 , 2 , 1 , - 1 , - 1 };
int N = arr.length;
int M = 10 ;
int result = countArray(arr, N, M);
System.out.println( "Number of valid arrays: " + result);
}
}
|
Python3
def check(arr):
N = len (arr)
for i in range ( 1 , N):
if arr[i] ! = - 1 and arr[i - 1 ] ! = - 1 and abs (arr[i] - arr[i - 1 ]) > 1 :
return False
return True
def generate(arr, pos, N, M, s):
if pos = = N:
if check(arr):
s.add( tuple (arr))
return
if arr[pos] ! = - 1 :
generate(arr, pos + 1 , N, M, s)
else :
for i in range ( 1 , M + 1 ):
arr[pos] = i
generate(arr, pos + 1 , N, M, s)
arr[pos] = - 1
def count_array(arr, M):
N = len (arr)
s = set ()
generate(arr, 0 , N, M, s)
return len (s)
if __name__ = = "__main__" :
arr = [ 4 , - 1 , 2 , 1 , - 1 , - 1 ]
N = len (arr)
M = 10
result = count_array(arr, M)
print (result)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static bool Check( int [] arr, int N)
{
for ( int i = 1; i < N; i++)
{
if (arr[i] != -1 && arr[i - 1] != -1 && Math.Abs(arr[i] - arr[i - 1]) > 1)
{
return false ;
}
}
return true ;
}
static void Generate( int [] arr, int pos, int N, int M, HashSet<List< int >> s)
{
if (pos == N)
{
if (Check(arr, N))
{
s.Add( new List< int >(arr));
}
return ;
}
if (arr[pos] != -1)
{
Generate(arr, pos + 1, N, M, s);
}
else
{
for ( int i = 1; i <= M; i++)
{
arr[pos] = i;
Generate(arr, pos + 1, N, M, s);
arr[pos] = -1;
}
}
}
static int CountArrays( int [] arr, int M)
{
HashSet<List< int >> s = new HashSet<List< int >>();
Generate(arr, 0, arr.Length, M, s);
return s.Count;
}
static void Main()
{
int [] arr = { 4, -1, 2, 1, -1, -1 };
int M = 10;
Console.WriteLine(CountArrays(arr, M));
}
}
|
Javascript
function check(arr, N) {
for (let i = 1; i < N; i++) {
if (arr[i] !== -1 && arr[i - 1] !== -1 && Math.abs(arr[i] - arr[i - 1]) > 1) {
return false ;
}
}
return true ;
}
function generate(arr, pos, N, M, s) {
if (pos === N) {
if (check(arr, N)) {
s.add([...arr]);
}
return ;
}
if (arr[pos] !== -1) {
generate(arr, pos + 1, N, M, s);
} else {
for (let i = 1; i <= M; i++) {
arr[pos] = i;
generate(arr, pos + 1, N, M, s);
arr[pos] = -1;
}
}
}
function countArray(arr, N, M) {
const s = new Set();
generate(arr, 0, N, M, s);
return s.size;
}
const arr = [4, -1, 2, 1, -1, -1];
const N = arr.length;
const M = 10;
console.log(countArray(arr, N, M));
|
Time Complexity: O(M^N * N), where M is the upper bound of the values that can be filled in the array, and N is the size of the array.
Auxiliary Space: O(M * N), which comes from the set s used to store the distinct arrays.
Approach: The given problem can be solved using Dynamic Programming based on the following observations:
- Consider a 2D array, say dp[][] where dp[i][j] represents the count of valid arrays of length i+1 having their last element as j.
- Since the absolute difference between any adjacent elements must be at most 1, so for any integer j, the valid adjacent integer can be j-1, j, and j+1. Therefore, any state dp[i][j] can be calculated using the following relation:
dp[ i ][ j ] = dp[ i-1 ][ j ] + dp[ i-1 ][ j-1 ] + dp[ i-1 ][ j+1 ]
- In cases where arr[i] = -1, calculate dp[i][j] = (dp[i-1][j] + dp[i-1][j-1] + dp[i-1][j+1]) for all values of j in the range [1, M].
- In cases where arr[i] != -1, calculate dp[i][j] = (dp[i-1][j] + dp[i-1][j-1] + dp[i-1][j+1]) for j = arr[i].
- Note that in cases where arr[0] = -1, all values in range [1, M] are reachable as the 1st array element, therefore initialize dp[0][j] = 1 for all j in the range [1, M] otherwise initialize dp[0][arr[0]] = 1.
- The required answer will be the sum of all values of dp[N – 1][j] for all j in the range [1, M].
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countArray( int arr[], int N, int M)
{
int dp[N][M + 2];
memset (dp, 0, sizeof dp);
if (arr[0] == -1) {
for ( int j = 1; j <= M; j++) {
dp[0][j] = 1;
}
}
else {
dp[0][arr[0]] = 1;
}
for ( int i = 1; i < N; i++) {
if (arr[i] != -1) {
int j = arr[i];
dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j]
+ dp[i - 1][j + 1];
}
if (arr[i] == -1) {
for ( int j = 1; j <= M; j++) {
dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j]
+ dp[i - 1][j + 1];
}
}
}
int arrCount = 0;
for ( int j = 1; j <= M; j++) {
arrCount += dp[N - 1][j];
}
return arrCount;
}
int main()
{
int arr[] = { 4, -1, 2, 1, -1, -1 };
int N = sizeof (arr) / sizeof (arr[0]);
int M = 10;
cout << countArray(arr, N, M);
return 0;
}
|
Java
class GFG
{
public static int countArray( int arr[], int N, int M)
{
int [][] dp = new int [N][M + 2 ];
for ( int i = 0 ; i < N; i++) {
for ( int j = 0 ; j < M + 2 ; j++) {
dp[i][j] = 0 ;
}
}
if (arr[ 0 ] == - 1 )
{
for ( int j = 1 ; j <= M; j++) {
dp[ 0 ][j] = 1 ;
}
} else {
dp[ 0 ][arr[ 0 ]] = 1 ;
}
for ( int i = 1 ; i < N; i++) {
if (arr[i] != - 1 ) {
int j = arr[i];
dp[i][j] += dp[i - 1 ][j - 1 ] + dp[i - 1 ][j] + dp[i - 1 ][j + 1 ];
}
if (arr[i] == - 1 ) {
for ( int j = 1 ; j <= M; j++) {
dp[i][j] += dp[i - 1 ][j - 1 ] + dp[i - 1 ][j] + dp[i - 1 ][j + 1 ];
}
}
}
int arrCount = 0 ;
for ( int j = 1 ; j <= M; j++) {
arrCount += dp[N - 1 ][j];
}
return arrCount;
}
public static void main(String args[]) {
int arr[] = { 4 , - 1 , 2 , 1 , - 1 , - 1 };
int N = arr.length;
int M = 10 ;
System.out.println(countArray(arr, N, M));
}
}
|
Python3
def countArray(arr, N, M):
dp = [[ 0 for i in range (M + 2 )] for j in range (N)]
if (arr[ 0 ] = = - 1 ):
for j in range ( 1 ,M + 1 , 1 ):
dp[ 0 ][j] = 1
else :
dp[ 0 ][arr[ 0 ]] = 1
for i in range ( 1 , N, 1 ):
if (arr[i] ! = - 1 ):
j = arr[i]
dp[i][j] + = dp[i - 1 ][j - 1 ] + dp[i - 1 ][j] + dp[i - 1 ][j + 1 ]
if (arr[i] = = - 1 ):
for j in range ( 1 ,M + 1 , 1 ):
dp[i][j] + = dp[i - 1 ][j - 1 ] + dp[i - 1 ][j] + dp[i - 1 ][j + 1 ]
arrCount = 0
for j in range ( 1 ,M + 1 , 1 ):
arrCount + = dp[N - 1 ][j]
return arrCount
if __name__ = = '__main__' :
arr = [ 4 , - 1 , 2 , 1 , - 1 , - 1 ]
N = len (arr)
M = 10
print (countArray(arr, N, M))
|
C#
using System;
public class GFG
{
public static int countArray( int []arr, int N, int M)
{
int [,] dp = new int [N, M + 2];
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < M + 2; j++) {
dp[i, j] = 0;
}
}
if (arr[0] == -1)
{
for ( int j = 1; j <= M; j++) {
dp[0, j] = 1;
}
} else {
dp[0, arr[0]] = 1;
}
for ( int i = 1; i < N; i++) {
if (arr[i] != -1) {
int j = arr[i];
dp[i, j] += dp[i - 1, j - 1] + dp[i - 1, j] + dp[i - 1, j + 1];
}
if (arr[i] == -1) {
for ( int j = 1; j <= M; j++) {
dp[i, j] += dp[i - 1, j - 1] + dp[i - 1, j] + dp[i - 1, j + 1];
}
}
}
int arrCount = 0;
for ( int j = 1; j <= M; j++) {
arrCount += dp[N - 1, j];
}
return arrCount;
}
public static void Main(String[] args) {
int []arr = { 4, -1, 2, 1, -1, -1 };
int N = arr.Length;
int M = 10;
Console.WriteLine(countArray(arr, N, M));
}
}
|
Javascript
function countArray(arr, N, M) {
let dp = new Array(N);
for (let i = 0; i < dp.length; i++) {
dp[i] = new Array(M + 2).fill(0);
}
if (arr[0] == -1) {
for (let j = 1; j <= M; j++) {
dp[0][j] = 1;
}
}
else {
dp[0][arr[0]] = 1;
}
for (let i = 1; i < N; i++) {
if (arr[i] != -1) {
let j = arr[i];
dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j]
+ dp[i - 1][j + 1];
}
if (arr[i] == -1) {
for (let j = 1; j <= M; j++) {
dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j]
+ dp[i - 1][j + 1];
}
}
}
let arrCount = 0;
for (let j = 1; j <= M; j++) {
arrCount += dp[N - 1][j];
}
return arrCount;
}
let arr = [4, -1, 2, 1, -1, -1];
let N = arr.length;
let M = 10;
document.write(countArray(arr, N, M));
|
Time Complexity: O(N*M)
Auxiliary Space: O(N*M)
Share your thoughts in the comments
Please Login to comment...