Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Color N boxes using M colors such that K boxes have different color from the box on its left
Next article icon

Color N boxes using M colors such that K boxes have different color from the box on its left

Last Updated : 29 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given N number of boxes arranged in a row and M number of colors. The task is to find the number of ways to paint those N boxes using M colors such that there are exactly K boxes with a color different from the color of the box on its left. Print this answer modulo 998244353.
Examples: 
 

Input: N = 3, M = 3, K = 0 
Output: 3 
Since the value of K is zero, no box can have a different color from color of the box on its left. Thus, all boxes should be painted with same color and since there are 3 types of colors, so there are total 3 ways. 
Input: N = 3, M = 2, K = 1 
Output: 4 
Let's number the colors as 1 and 2. Four possible sequences of painting 3 boxes with 1 box having different color from color of box on its left are (1 2 2), (1 1 2), (2 1 1) (2 2 1) 
 


Prerequisites : Dynamic Programming
 


Approach: This problem can be solved using dynamic programming where dp[i][j] will denote the number of ways to paint i boxes using M colors such that there are exactly j boxes with a color different from the color of the box on its left. For every current box except 1st, either we can paint the same color as painted on its left box and solve for dp[i - 1][j] or we can paint it with remaining M - 1 color and solve for dp[i - 1][j - 1] recursively.

Steps to follow to according to above approach:

  • If idx is greater than N, then check if diff is equal to K.
    • *If diff is equal to K, then return 1.
               *Else, return 0.
  • If the result for the current value of idx and diff is not equal to -1 then return the precomputed result dp[idx][diff][/diff].
  • Otherwise, recursively call solve() function with idx+1, diff, N, M, and K and store the result in the variable ans.
  • recursively call solve() function with idx+1, diff+1, N, M, and K, and multiply the result with (M-1).
  • add the value obtained in step 5 to the result obtained in step 4, and take its modulo with MOD.
  • store the result obtained in step 6 in the dp array for the current value of idx and diff, and return the same value.


Below is the code to implement the above approach: 
 

C++
// CPP Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left #include <bits/stdc++.h> using namespace std;  const int MOD = 998244353;  vector<vector<int>> dp;  // This function returns the required number // of ways where idx is the current index and // diff is number of boxes having different // color from box on its left int solve(int idx, int diff, int N, int M, int K) {     // Base Case     if (idx > N) {         if (diff == K)             return 1;         return 0;     }      // If already computed     if (dp[idx][ diff] != -1)         return dp[idx][ diff];      // Either paint with same color as     // previous one     int ans = solve(idx + 1, diff, N, M, K);      // Or paint with remaining (M - 1)     // colors     ans = ans % MOD + ((M - 1) % MOD * solve(idx + 1, diff + 1, N, M, K) % MOD) % MOD;      return dp[idx][ diff] = ans; }  // Driver code int main() {     int N = 3, M = 3, K = 0;     dp = vector<vector<int>>(N+1,vector<int>(N+1,-1));      // Multiply M since first box can be     // painted with any of the M colors and     // start solving from 2nd box     cout << (M * solve(2, 0, N, M, K)) << endl;      return 0; } 
Java
// Java Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left  class GFG {          static int M = 1001;     static int MOD = 998244353;      static int[][] dp = new int[M][M];      // This function returns the required number     // of ways where idx is the current index and     // diff is number of boxes having different     // color from box on its left     static int solve(int idx, int diff,                         int N, int M, int K)     {         // Base Case         if (idx > N)          {             if (diff == K)                 return 1;             return 0;         }          // If already computed         if (dp[idx][ diff] != -1)             return dp[idx][ diff];          // Either paint with same color as         // previous one         int ans = solve(idx + 1, diff, N, M, K);          // Or paint with remaining (M - 1)         // colors         ans += (M - 1) * solve(idx + 1,                  diff + 1, N, M, K);          return dp[idx][ diff] = ans % MOD;     }      // Driver code     public static void main (String[] args)      {         int N = 3, M = 3, K = 0;         for(int i = 0; i <= M; i++)             for(int j = 0; j <= M; j++)                 dp[i][j] = -1;              // Multiply M since first box can be         // painted with any of the M colors and         // start solving from 2nd box         System.out.println((M * solve(2, 0, N, M, K)));     } }  // This code is contributed by mits 
Python3
# Python3 Program to Paint N boxes using M  # colors such that K boxes have color  # different from color of box on its left   M = 1001;  MOD = 998244353;   dp = [[-1]* M ] * M  # This function returns the required number  # of ways where idx is the current index and  # diff is number of boxes having different  # color from box on its left  def solve(idx, diff, N, M, K) :          # Base Case      if (idx > N) :          if (diff == K) :             return 1          return 0      # If already computed      if (dp[idx][ diff] != -1) :         return dp[idx];       # Either paint with same color as      # previous one      ans = solve(idx + 1, diff, N, M, K);       # Or paint with remaining (M - 1)      # colors      ans += (M - 1) * solve(idx + 1, diff + 1, N, M, K);       dp[idx][ diff] = ans % MOD;           return dp[idx][ diff]  # Driver code  if __name__ == "__main__" :       N = 3     M = 3     K = 0       # Multiply M since first box can be      # painted with any of the M colors and      # start solving from 2nd box      print(M * solve(2, 0, N, M, K))   # This code is contributed by Ryuga 
C#
// C# Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left using System; class GFG {      static int M = 1001; static int MOD = 998244353;  static int[,] dp = new int[M, M];  // This function returns the required number // of ways where idx is the current index and // diff is number of boxes having different // color from box on its left static int solve(int idx, int diff,                  int N, int M, int K) {     // Base Case     if (idx > N)      {         if (diff == K)             return 1;         return 0;     }      // If already computed     if (dp[idx, diff] != -1)         return dp[idx, diff];      // Either paint with same color as     // previous one     int ans = solve(idx + 1, diff, N, M, K);      // Or paint with remaining (M - 1)     // colors     ans += (M - 1) * solve(idx + 1,                  diff + 1, N, M, K);      return dp[idx, diff] = ans % MOD; }  // Driver code public static void Main ()  {     int N = 3, M = 3, K = 0;     for(int i = 0; i <= M; i++)         for(int j = 0; j <= M; j++)             dp[i, j] = -1;      // Multiply M since first box can be     // painted with any of the M colors and     // start solving from 2nd box     Console.WriteLine((M * solve(2, 0, N, M, K))); } }  // This code is contributed by chandan_jnu 
JavaScript
<script>      // JavaScript Program to Paint N boxes using M     // colors such that K boxes have color     // different from color of box on its left          let m = 1001;     let MOD = 998244353;        let dp = new Array(m);     for(let i = 0; i < m; i++)     {         dp[i] = new Array(m);         for(let j = 0; j < m; j++)         {             dp[i][j] = 0;         }     }        // This function returns the required number     // of ways where idx is the current index and     // diff is number of boxes having different     // color from box on its left     function solve(idx, diff, N, M, K)     {         // Base Case         if (idx > N)          {             if (diff == K)                 return 1;             return 0;         }            // If already computed         if (dp[idx][ diff] != -1)             return dp[idx][ diff];            // Either paint with same color as         // previous one         let ans = solve(idx + 1, diff, N, M, K);            // Or paint with remaining (M - 1)         // colors         ans += (M - 1) * solve(idx + 1,                  diff + 1, N, M, K);           dp[idx][ diff] = ans % MOD;         return dp[idx][ diff];     }          let N = 3, M = 3, K = 0;     for(let i = 0; i <= M; i++)       for(let j = 0; j <= M; j++)         dp[i][j] = -1;      // Multiply M since first box can be     // painted with any of the M colors and     // start solving from 2nd box     document.write((M * solve(2, 0, N, M, K)));      </script> 
PHP
<?php // PHP Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left  $M = 1001; $MOD = 998244353;  $dp = array_fill(0, $M,       array_fill(0, $M, -1));  // This function returns the required number // of ways where idx is the current index  // and diff is number of boxes having  // different color from box on its left function solve($idx, $diff, $N, $M, $K) {     global $dp, $MOD;          // Base Case     if ($idx > $N)      {         if ($diff == $K)             return 1;         return 0;     }      // If already computed     if ($dp[$idx][$diff] != -1)         return $dp[$idx][$diff];      // Either paint with same color      // as previous one     $ans = solve($idx + 1, $diff, $N, $M, $K);      // Or paint with remaining (M - 1)     // colors     $ans += ($M - 1) * solve($idx + 1,              $diff + 1, $N, $M, $K);      return $dp[$idx][$diff] = $ans % $MOD; }  // Driver code $N = 3; $M = 3; $K = 0;  // Multiply M since first box can be // painted with any of the M colors and // start solving from 2nd box echo ($M * solve(2, 0, $N, $M, $K));  // This code is contributed by chandan_jnu ?> 

Output
3

Time Complexity: O(M*M)
Auxiliary Space: O(M*M)

Efficient approach : Using DP Tabulation method ( Iterative approach )

The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because memoization method needs extra stack space of recursion calls.

Steps to solve this problem :

  • Create a DP to store the solution of the subproblems .
  • Initialize the DP with base cases by initializing the first row of DP.
  • Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP.
  • Return the final solution stored in dp[1][K].

Implementation :

C++
// CPP Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left  #include <bits/stdc++.h> using namespace std;  const int MOD = 998244353;  int dp[2][1010];  // This function returns the required number // of ways where idx is the current index and // diff is number of boxes having different // color from box on its left int solve(int N, int M, int K) {     // Initialize the first row of dp table     for (int i = 0; i <= N; i++) {         dp[0][i] = 1;     }      // Process the remaining rows     for (int i = 2; i <= N + 1; i++) {         for (int j = 0; j <= N; j++) {             int ans = dp[0][j];              if (j == 0) {                 ans = (M * dp[1][j]) % MOD;             } else {                 ans = (ans % MOD + ((M - 1) % MOD * dp[1][j - 1]) % MOD) % MOD;             }              dp[0][j] = ans;         }          // Swap the arrays         swap(dp[0], dp[1]);     }          // return final answer     return dp[1][K]; }  // Driver code int main() {     int N = 3, M = 3, K = 0;          // function call     cout << (M * solve(N, M, K + 1)) % MOD << endl;      return 0; } 
Java
// Java Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left  import java.util.*;  public class Main {   static final int MOD = 998244353;  static int[][] dp;  // This function returns the required number // of ways where idx is the current index and // diff is number of boxes having different // color from box on its left static int solve(int N, int M, int K) {     // Initialize the first row of dp table     for (int i = 0; i <= N; i++) {         dp[0][i] = 1;     }      // Process the remaining rows     for (int i = 2; i <= N + 1; i++) {         for (int j = 0; j <= N; j++) {             int ans = dp[0][j];              if (j == 0) {                 ans = (M * dp[1][j]) % MOD;             } else {                 ans = (ans % MOD + ((M - 1) % MOD * dp[1][j - 1]) % MOD) % MOD;             }              dp[0][j] = ans;         }          // Swap the arrays         int[] temp = dp[0];         dp[0] = dp[1];         dp[1] = temp;     }      // return final answer     return dp[1][K]; }  // Driver code public static void main(String[] args) {     int N = 3, M = 3, K = 0;      // Initialize dp array     dp = new int[2][1010];      // function call     System.out.println((M * solve(N, M, K + 1)) % MOD); } } 
Python3
MOD = 998244353  # This function returns the required number # of ways where idx is the current index and # diff is number of boxes having different # color from box on its left def solve(N, M, K):     global dp          # Initialize the first row of dp table     for i in range(N+1):         dp[0][i] = 1      # Process the remaining rows     for i in range(2, N+2):         for j in range(N+1):             ans = dp[0][j]              if j == 0:                 ans = (M * dp[1][j]) % MOD             else:                 ans = (ans % MOD + ((M - 1) % MOD * dp[1][j - 1]) % MOD) % MOD              dp[0][j] = ans          # Swap the arrays         dp[0], dp[1] = dp[1], dp[0]      # return final answer     return dp[1][K]  # Driver code if __name__ == '__main__':     N, M, K = 3, 3, 0      # Initialize dp array     dp = [[0] * 1010 for _ in range(2)]      # function call     print((M * solve(N, M, K+1)) % MOD) 
C#
using System;  public class MainClass {     static readonly int MOD = 998244353;     static int[,] dp;      // This function returns the required number     // of ways where idx is the current index and     // diff is the number of boxes having a different     // color from the box on its left     static int Solve(int N, int M, int K)     {         // Initialize the first row of dp table         for (int i = 0; i <= N; i++)         {             dp[0, i] = 1;         }          // Process the remaining rows         for (int i = 2; i <= N + 1; i++)         {             for (int j = 0; j <= N; j++)             {                 int ans = dp[0, j];                  if (j == 0)                 {                     ans = (int)((M * (long)dp[1, j]) % MOD);                 }                 else                 {                     ans = (int)((ans % MOD + ((M - 1) % MOD * (long)dp[1, j - 1]) % MOD) % MOD);                 }                  dp[0, j] = ans;             }              // Swap the arrays             for (int k = 0; k <= N; k++)             {                 int temp = dp[0, k];                 dp[0, k] = dp[1, k];                 dp[1, k] = temp;             }         }          // return the final answer         return dp[1, K];     }      // Driver code     public static void Main(string[] args)     {         int N = 3, M = 3, K = 0;          // Initialize dp array         dp = new int[2, 1010];          // Function call         Console.WriteLine((int)((M * (long)Solve(N, M, K + 1)) % MOD));     } } 
JavaScript
// JavaScript Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left  const MOD = 998244353;  // This function returns the required number // of ways where idx is the current index and // diff is the number of boxes having a different // color from the box on its left function solve(N, M, K) {     // Initialize a 2D array for dynamic programming     const dp = new Array(2).fill().map(() => new Array(N + 1).fill(0));      // Initialize the first row of dp table     for (let i = 0; i <= N; i++) {         dp[0][i] = 1;     }      // Process the remaining rows     for (let i = 2; i <= N + 1; i++) {         for (let j = 0; j <= N; j++) {             let ans = dp[0][j];              if (j === 0) {                 ans = (M * dp[1][j]) % MOD;             } else {                 ans = (ans % MOD + ((M - 1) % MOD * dp[1][j - 1]) % MOD) % MOD;             }              dp[0][j] = ans;         }          // Swap the arrays         [dp[0], dp[1]] = [dp[1], dp[0]];     }      // Return the final answer     return dp[1][K]; }  // Driver code const N = 3, M = 3, K = 0;  // Function call console.log((M * solve(N, M, K + 1)) % MOD);  // This code is contributed by prasad264 


Output: 

3


 

Time Complexity:  O(N * N)
Auxiliary Space:  O(N)


Next Article
Color N boxes using M colors such that K boxes have different color from the box on its left

N

Nishant Tanwar
Improve
Article Tags :
  • Algorithms
  • Dynamic Programming
  • Mathematical
  • Technical Scripter
  • Competitive Programming
  • DSA
  • Technical Scripter 2018
Practice Tags :
  • Algorithms
  • Dynamic Programming
  • Mathematical

Similar Reads

    Ways to color a skewed tree such that parent and child have different colors
    Given a skewed tree (Every node has at most one child) with N nodes and K colors. You have to assign a color from 1 to K to each node such that parent and child has different colors. Find the maximum number of ways of coloring the nodes. Examples: Input : N = 2, K = 2. Output : Let A1 and A2 be the
    6 min read
    Color tree with minimum colors such that colors of edges incident to a vertex are different
    Given a tree with N nodes. The task is to color the tree with the minimum number of colors(K) such that the colors of the edges incident to a vertex are different. Print K in first-line and then in next line print N - 1 space-separated integer represents the colors of the edges. Examples: Input: N =
    10 min read
    Ways to fill N positions using M colors such that there are exactly K pairs of adjacent different colors
    Given three integers N, M and K. The task is to find the number of ways to fill N positions using M colors such that there are exactly K pairs of different adjacent colors. Examples: Input: N = 3, M = 2, K = 1 Output: 4 Let the colors be 1 and 2, so the ways are: 1, 1, 2 1, 2, 2 2, 2, 1 2, 1, 1 The
    12 min read
    Check if N indices of given Array can be colored by M colors using one color at most K times
    Find an arrangement of M colors for N indices such that no two adjacent indices have same color and each color can be used at most K times. If no such arrangement exists, output -1. Examples: Input: N = 6, M = 4, K = 2Output: 1 2 3 4 1 2 Explanation: Color 1 is assigned to the 1-st index. Color 2 is
    7 min read
    Maximize the diamonds by choosing different colour diamonds from adjacent boxes
    Given two integers N and M where N is the number of boxes placed in a row and M is the number of colours of diamonds which are distributed in these boxes such that each box contains at least 1 diamond in it. Each diamond has a colour and a value represented by a M * N matrix where mat[i][j] denotes
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences