VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-of-ways-to-color-n-k-blocks-using-given-operation/

⇱ Number of ways to color N-K blocks using given operation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of ways to color N-K blocks using given operation

Last Updated : 12 Jul, 2025

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:
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: 

  1. Traverse each block from 1 to N.
  2. If the current block(say b) is not colored, then check whether one of the adjacent blocks is colored or not.
  3. If the adjacent block is colored, then color the current block and recursively iterate to find the next uncolored block.
  4. After the above recursive call ends, then, uncolored the block for the blockquotevious recursive call and repeat the above steps for the next uncolored block.
  5. The count of coloring the blocks in all the above recursive calls gives the number of ways to color the uncolored block.


Below is the implementation of the above approach: 


Output: 
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: 


Output: 
4

 

Time Complexity: O(N2

Auxiliary Space: O(52 * 104)
 

Comment