![]() |
VOOZH | about |
You know that an array arr[] has N integers between 1 and M, and the absolute difference between two adjacent values is at most 1. Given a description of the array where some values may be unknown, your task is to count the number of arrays that match the description.
Examples:
Input: N = 3, M = 5, arr[] = {2, 0, 2}
Output: 3
Explanation: There are 3 arrays that match the description:
- First array: arr[] = {2, 1, 2}
- Second array: arr[] = {2, 2, 2}
- Third array: arr[] = {2, 3, 2}
Input: N = 1, M = 5, arr[] = {2}
Output: 1
Explanation: There is only one array that matches the description and that is {2}.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Dynamic Programming. Maintain a dp[][] array, such that dp[i][j] stores the number of ways to have arr[i] = j.
Initially, let's focus on the first index, i = 0. So, there are 2 possible values of arr[0].
- If arr[0] = 0, then we can have arr[0] as any value from 1 to M. So, for all values j from 1 to M, there is only one way to have arr[i] = j. Therefore, for all values of j from 1 to M, dp[0][j] = 1.
- If arr[0] != 0, then it means that arr[0] already has a value and we cannot put any other value at the first index. Therefore, we have dp[0][arr[0]] = 1.
Now, for all indices i from 1 to N, again there are two possible values of arr[i].
- If arr[i] = 0, then the number of ways we can have arr[i] = val is the sum of number of ways we can have arr[i - 1] = val - 1, arr[i-1] = val and arr[i - 1] = val + 1. Therefore, for all values of j from 1 to M, dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] + dp[i - 1][j + 1].
- If arr[i] != 0, then it means that arr[i] already has a value and we cannot put any other value at index i. So, the number of ways will be sum of number of ways we can have arr[i - 1] = arr[i] - 1, arr[i-1] = arr[i] and arr[i - 1] = arr[i] + 1. Therefore, we have dp[i][arr[i]] = dp[i - 1][arr[i] - 1] + dp[i - 1][arr[i]] + dp[i - 1][arr[i] + 1].
The final answer will be sum of number of ways we can put any value j at the last index, that is sum of dp[N - 1][j] for all j from 1 to M.
Step-by-step algorithm:
Below is the implementation of the algorithm:
3
Time Complexity: O(N * M), where N is the size of array arr[] and M is the range of values in arr[].
Auxiliary Space: O(N * M)