Given two integers n and m, where n represent some paintings numbered from 1 to n and m represent some colours 1 to m with unlimited amount. The task is to find the number of ways to paint the paintings such that no two consecutive paintings have the same colors.
Note: Answer must be calculated in modulo 10^9 +7 as answer can be very large.
Input: n = 4, m = 2 Output: 2 Input: n = 4, m = 6 Output: 750
Asked in : National Instruments
The total number of given color is m and the total paintings are from 1 to n. As per the condition of no two adjacent painting having the same color, first painting can be painted by anyone out of n colors and the rest of any painting can be painted by any of n-1 color except the color used for the painting just preceding that. Hence if we derive the solution for total number of ways,
n * (m-1)^(n-1) is the actual answer.
Now, this can be either calculated by simple iteration or by the method of efficient power calculation in O(logn) time.
Below is the implementation of the above approach:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Ways to paint stairs with two colors such that two adjacent are not yellow
- Number of ways to paint a tree of N nodes with K distinct colors with given conditions
- Number of ways to paint K cells in 3 x N grid such that no P continuous columns are left unpainted
- Ways to color a 3*N board using 4 colors
- Ways to color a skewed tree such that parent and child have different colors
- Number of ways to form an array with distinct adjacent elements
- Ways to arrange Balls such that adjacent balls are of different types
- Maximum area of triangle having different vertex colors
- Minimum steps to color the tree with given colors
- Number of strictly increasing Buildings from right with distinct Colors
- Minimum colors required such that edges forming cycle do not have same color
- Longest subsequence with different adjacent characters
- Maximum sum of difference of adjacent elements
- Check whether given three numbers are adjacent primes
- Permutations of string such that no two vowels are adjacent
- Sum of the count of number of adjacent squares in an M X N grid
- Smallest number possible by swapping adjacent even odd pairs
- Maximum sum in circular array such that no two elements are adjacent | Set 2
- Rearrange characters in a string such that no two adjacent are same using hashing
- Distinct adjacent elements in a binary array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.