![]() |
VOOZH | about |
Given N blocks, out of which K is colored. These K-colored blocks are denoted by an array arr[]. The task is to count the number of ways to color the remaining uncolored blocks such that only any one of the adjacent blocks, of a colored block, can be colored in one step. Print the answer with modulo 109+7.
Examples:
Input: N = 6, K = 3, arr[] = {1, 2, 6}
Output: 4
Explanation:
The following are the 4 ways to color the blocks(each set represents the order in which blocks are colored):
1. {3, 4, 5}
2. {3, 5, 4}
3. {5, 3, 4}
4. {5, 4, 3}
Input: N = 9, K = 3, A = [3, 6, 7]
Output: 180
Naive Approach: The idea is to use recursion. Below are the steps:
Below is the implementation of the above approach:
4
Time Complexity: O(NN-K)
Auxiliary Space: O(N)
Efficient Approach: For solving this problem efficiently we will use the concept of Permutation and Combination. Below are the steps:
1. If the number of blocks between two consecutive colored blocks is x, then the number of ways to color these set of blocks is given by:
ways = 2x-1
2. Coloring each set of uncolored blocks is independent of the other. Suppose there are x blocks in one section and y blocks in the other section. To find the total combination when the two sections are merged is given by:
total combinations =
3. Sort the colored block indices to find the length of each uncolored block section and iterate and find the combination of each two-section using the above formula.
4. Find the Binomial Coefficient using the approach discussed in this article.
Below is the implementation of the above approach:
4
Time Complexity: O(N2)
Auxiliary Space: O(52 * 104)