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 {
// Function to check if a given array satisfies the conditions
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;
}
// Recursively generate arrays and add valid triplets to the set
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;
}
}
}
// Count the number of valid arrays
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
# Function to check if the array satisfies the given condition
def check(arr):
N = len(arr)
for i in range(1, N):
# Check if adjacent elements are not -1 and their absolute difference is greater than 1
if arr[i] != -1 and arr[i - 1] != -1 and abs(arr[i] - arr[i - 1]) > 1:
return False
return True
# Function to generate all possible combinations of the array
def generate(arr, pos, N, M, s):
# If we have generated a complete array, check if it satisfies
# the condition and add to the set
if pos == N:
if check(arr):
s.add(tuple(arr))
return
# If the current position is not -1, move to the next position
if arr[pos] != -1:
generate(arr, pos + 1, N, M, s)
# If the current position is -1, try all possible values from 1 to M
else:
for i in range(1, M + 1):
arr[pos] = i
generate(arr, pos + 1, N, M, s)
arr[pos] = -1
# Function to count the number of unique arrays that satisfy the condition
def count_array(arr, M):
N = len(arr)
s = set() # Create a set to store unique arrays
generate(arr, 0, N, M, s) # Generate all possible arrays
return len(s) # Return the count of unique arrays
# Driver code
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
{
// Function to check if an array meets the constraints
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;
}
// Recursive function to generate arrays and count valid ones
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)); // Add the valid array to the HashSet
}
return;
}
if (arr[pos] != -1)
{
Generate(arr, pos + 1, N, M, s);
}
else
{
for (int i = 1; i <= M; i++)
{
arr[pos] = i; // Set the value at the current position
Generate(arr, pos + 1, N, M, s); // Recursively generate the next position
arr[pos] = -1; // Reset the value for backtracking
}
}
}
// Function to count the number of arrays that meet the constraints
static int CountArrays(int[] arr, int M)
{
HashSet<List<int>> s = new HashSet<List<int>>();
Generate(arr, 0, arr.Length, M, s); // Start array generation from the beginning
return s.Count; // Return the count of valid arrays
}
static void Main()
{
int[] arr = { 4, -1, 2, 1, -1, -1 };
int M = 10;
Console.WriteLine(CountArrays(arr, M)); // Output the count of valid arrays
}
}
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]); // Using spread operator to create a copy of the array
}
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;
}
// Example usage
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++
// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the count of possible
// arrays such that the absolute difference
// between any adjacent elements is atmost 1
int countArray(int arr[], int N, int M)
{
// Stores the dp states where dp[i][j]
// represents count of arrays of length
// i+1 having their last element as j
int dp[N][M + 2];
memset(dp, 0, sizeof dp);
// Case where 1st array element is missing
if (arr[0] == -1) {
// All integers in range [1, M]
// are reachable
for (int j = 1; j <= M; j++) {
dp[0][j] = 1;
}
}
else {
// Only reachable integer is arr[0]
dp[0][arr[0]] = 1;
}
// Iterate through all values of i
for (int i = 1; i < N; i++) {
// If arr[i] is not missing
if (arr[i] != -1) {
// Only valid value of j is arr[i]
int j = arr[i];
dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j]
+ dp[i - 1][j + 1];
}
// If arr[i] is missing
if (arr[i] == -1) {
// Iterate through all possible
// values of j in range [1, M]
for (int j = 1; j <= M; j++) {
dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j]
+ dp[i - 1][j + 1];
}
}
}
// Stores the count of valid arrays
int arrCount = 0;
// Calculate the total count of
// valid arrays
for (int j = 1; j <= M; j++) {
arrCount += dp[N - 1][j];
}
// Return answer
return arrCount;
}
// Driver Code
int main()
{
int arr[] = { 4, -1, 2, 1, -1, -1 };
int N = sizeof(arr) / sizeof(arr[0]);
int M = 10;
// Function Call
cout << countArray(arr, N, M);
return 0;
}
Java
// Java program of the above approach
class GFG
{
// Function to find the count of possible
// arrays such that the absolute difference
// between any adjacent elements is atmost 1
public static int countArray(int arr[], int N, int M)
{
// Stores the dp states where dp[i][j]
// represents count of arrays of length
// i+1 having their last element as j
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;
}
}
// Case where 1st array element is missing
if (arr[0] == -1)
{
// All integers in range [1, M]
// are reachable
for (int j = 1; j <= M; j++) {
dp[0][j] = 1;
}
} else {
// Only reachable integer is arr[0]
dp[0][arr[0]] = 1;
}
// Iterate through all values of i
for (int i = 1; i < N; i++) {
// If arr[i] is not missing
if (arr[i] != -1) {
// Only valid value of j is arr[i]
int j = arr[i];
dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j] + dp[i - 1][j + 1];
}
// If arr[i] is missing
if (arr[i] == -1) {
// Iterate through all possible
// values of j in range [1, M]
for (int j = 1; j <= M; j++) {
dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j] + dp[i - 1][j + 1];
}
}
}
// Stores the count of valid arrays
int arrCount = 0;
// Calculate the total count of
// valid arrays
for (int j = 1; j <= M; j++) {
arrCount += dp[N - 1][j];
}
// Return answer
return arrCount;
}
// Driver Code
public static void main(String args[]) {
int arr[] = { 4, -1, 2, 1, -1, -1 };
int N = arr.length;
int M = 10;
// Function Call
System.out.println(countArray(arr, N, M));
}
}
// This code is contributed by _saurabh_jaiswal.
Python3
# Python 3 program of the above approach
# Function to find the count of possible
# arrays such that the absolute difference
# between any adjacent elements is atmost 1
def countArray(arr, N, M):
# Stores the dp states where dp[i][j]
# represents count of arrays of length
# i+1 having their last element as j
dp = [[0 for i in range(M+2)] for j in range(N)]
# Case where 1st array element is missing
if (arr[0] == -1):
# All integers in range [1, M]
# are reachable
for j in range(1,M+1,1):
dp[0][j] = 1
else:
# Only reachable integer is arr[0]
dp[0][arr[0]] = 1
# Iterate through all values of i
for i in range(1, N, 1):
# If arr[i] is not missing
if(arr[i] != -1):
# Only valid value of j is arr[i]
j = arr[i]
dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j] + dp[i - 1][j + 1]
# If arr[i] is missing
if (arr[i] == -1):
# Iterate through all possible
# values of j in range [1, M]
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]
# Stores the count of valid arrays
arrCount = 0
# Calculate the total count of
# valid arrays
for j in range(1,M+1,1):
arrCount += dp[N - 1][j]
# Return answer
return arrCount
# Driver Code
if __name__ == '__main__':
arr = [4, -1, 2, 1, -1, -1]
N = len(arr)
M = 10
# Function Call
print(countArray(arr, N, M))
# This code is contributed by SURENDRA_GANGWAR.
C#
// C# program of the above approach
using System;
public class GFG
{
// Function to find the count of possible
// arrays such that the absolute difference
// between any adjacent elements is atmost 1
public static int countArray(int []arr, int N, int M)
{
// Stores the dp states where dp[i][j]
// represents count of arrays of length
// i+1 having their last element as j
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;
}
}
// Case where 1st array element is missing
if (arr[0] == -1)
{
// All integers in range [1, M]
// are reachable
for (int j = 1; j <= M; j++) {
dp[0, j] = 1;
}
} else {
// Only reachable integer is arr[0]
dp[0, arr[0]] = 1;
}
// Iterate through all values of i
for (int i = 1; i < N; i++) {
// If arr[i] is not missing
if (arr[i] != -1) {
// Only valid value of j is arr[i]
int j = arr[i];
dp[i, j] += dp[i - 1, j - 1] + dp[i - 1, j] + dp[i - 1, j + 1];
}
// If arr[i] is missing
if (arr[i] == -1) {
// Iterate through all possible
// values of j in range [1, M]
for (int j = 1; j <= M; j++) {
dp[i, j] += dp[i - 1, j - 1] + dp[i - 1, j] + dp[i - 1, j + 1];
}
}
}
// Stores the count of valid arrays
int arrCount = 0;
// Calculate the total count of
// valid arrays
for (int j = 1; j <= M; j++) {
arrCount += dp[N - 1, j];
}
// Return answer
return arrCount;
}
// Driver Code
public static void Main(String[] args) {
int []arr = { 4, -1, 2, 1, -1, -1 };
int N = arr.Length;
int M = 10;
// Function Call
Console.WriteLine(countArray(arr, N, M));
}
}
// This code is contributed by AnkThon.
JavaScript
// JavaScript Program to implement
// the above approach
// Function to find the count of possible
// arrays such that the absolute difference
// between any adjacent elements is atmost 1
function countArray(arr, N, M) {
// Stores the dp states where dp[i][j]
// represents count of arrays of length
// i+1 having their last element as j
let dp = new Array(N);
// Loop to create 2D array using 1D array
for (let i = 0; i < dp.length; i++) {
dp[i] = new Array(M + 2).fill(0);
}
// Case where 1st array element is missing
if (arr[0] == -1) {
// All integers in range [1, M]
// are reachable
for (let j = 1; j <= M; j++) {
dp[0][j] = 1;
}
}
else {
// Only reachable integer is arr[0]
dp[0][arr[0]] = 1;
}
// Iterate through all values of i
for (let i = 1; i < N; i++) {
// If arr[i] is not missing
if (arr[i] != -1) {
// Only valid value of j is arr[i]
let j = arr[i];
dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j]
+ dp[i - 1][j + 1];
}
// If arr[i] is missing
if (arr[i] == -1) {
// Iterate through all possible
// values of j in range [1, M]
for (let j = 1; j <= M; j++) {
dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j]
+ dp[i - 1][j + 1];
}
}
}
// Stores the count of valid arrays
let arrCount = 0;
// Calculate the total count of
// valid arrays
for (let j = 1; j <= M; j++) {
arrCount += dp[N - 1][j];
}
// Return answer
return arrCount;
}
// Driver Code
let arr = [4, -1, 2, 1, -1, -1];
let N = arr.length;
let M = 10;
// Function Call
document.write(countArray(arr, N, M));
// This code is contributed by Potta Lokesh
Time Complexity: O(N*M)
Auxiliary Space: O(N*M)
Similar Reads
Count of numbers upto N having absolute difference of at most K between any two adjacent digits
Given an integer N, the task is to count the numbers up to N having an absolute difference of at most K between any two adjacent digits.Note: Count of integer 0 for any digits is considerable.Examples: Input: N = 20, K = 2 Output: 15 Explanation: The required numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
13 min read
Count of N digit numbers having absolute difference between adjacent digits as K
Given two integers N and K. The task is to count all positive integers with length N having an absolute difference between adjacent digits equal to K. Examples: Input: N = 4, K = 8Output: 3Explanation: The absolute difference between every consecutive digit of each number is 8. Three possible number
7 min read
Count triplets from a sorted array having difference between adjacent elements equal to D
Given a sorted array arr[] consisting of N positive integers and an integer D, the task is to find the number of triplets (i, j, k) such that arr[j] - arr[i] = D and arr[k] - arr[j] = D and 0 ? i < j < k < N. Examples: Input: arr[] = {1, 2, 4, 5, 7, 8, 10}, D = 3Output: 3Explanation:Followi
6 min read
Split array into K subarrays with minimum sum of absolute difference between adjacent elements
Given an array, arr[] of size N and an integer K, the task is to split the array into K subarrays minimizing the sum of absolute difference between adjacent elements of each subarray. Examples: Input: arr[] = {1, 3, -2, 5, -1}, K = 2Output: 13Explanation: Split the array into following 2 subarrays:
8 min read
Count of N-digit numbers whose absolute difference between adjacent digits is non-increasing
Given a positive integer N, the task is to count the number of N-digit numbers having absolute difference between consecutive digits in non-increasing order. Examples: Input: N = 1Output: 10Explanation:All numbers from 0 to 9 satisfy the given condition as there is only one digit. Input: N = 3Output
10 min read
Minimize sum of absolute differences between given Arrays by replacing at most 1 element from first Array
Given two arrays a[] and b[] of equal size. The task is to calculate the minimum sum of absolute differences for each index. It is allowed to replace at most 1 element of the first array with any value from the first array itself. Example: Input: a[] = {1, 9, 4, 2}, b[] = {2, 3, 7, 1}Output: 6Explan
9 min read
Count of array elements to be removed to make absolute difference between each pair same
Given an array arr[] consisting of N integers, the task is to find the minimum number of array elements that must be removed such that the absolute difference between each element pair is equal. Examples: Input: arr[] = {1, 2}Output: 0Explanation: There is only one pair of integers with absolute dif
8 min read
Absolute Difference of all pairwise consecutive elements in an array
Given an array of integers of N elements. The task is to print the absolute difference of all of the pairwise consecutive elements. Pairwise consecutive pairs of an array of size N are (a[i], a[i+1]) for all i ranging from 0 to N-2 Examples: Input: arr[] = {8, 5, 4, 3, 15, 20}Output: 3, 1, 1, 12, 5I
4 min read
Arrange first N natural numbers such that absolute difference between all adjacent elements > 1
Given an integer N. The task is to find the permutation of first N natural numbers such that the absolute difference between any two consecutive numbers > 1. If no such permutation is possible then print -1. Examples: Input: N = 5 Output: 5 3 1 4 2 Input: N = 3 Output: -1 Approach: There may be m
6 min read
Minimize sum of absolute difference between all pairs of array elements by decrementing and incrementing pairs by 1
Given an array arr[] ( 1-based indexing ) consisting of N integers, the task is to find the minimum sum of the absolute difference between all pairs of array elements by decrementing and incrementing any pair of elements by 1 any number of times. Examples: Input: arr[] = {1, 2, 3}Output: 0Explanatio
5 min read