Count of Arrays of size N having absolute difference between adjacent elements at most 1

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;} |
Python3
# Function to check if the array satisfies the given conditiondef 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 arraydef 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 conditiondef 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 codeif __name__ == "__main__":Â Â Â Â arr = [4, -1, 2, 1, -1, -1]Â Â Â Â Â Â N = len(arr)Â Â Â Â M = 10Â Â Â Â Â result = count_array(arr, M)Â Â Â Â Â Â Â print(result)Â |
5
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 1int 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 Codeint 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 approachclass 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 1def 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 Codeif __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 approachusing 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
<script>        // 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Â
    </script> |
5
Time Complexity: O(N*M)
Auxiliary Space: O(N*M)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



