Count of Arrays of size N having absolute difference between adjacent elements at most 1
Last Updated :
26 Jul, 2025
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
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