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.
Input: N = 6, M = 4, K = 2
Output: 1 2 3 4 1 2
Explanation: Color 1 is assigned to the 1-st index.
Color 2 is assigned to the 2-nd index, color 3 to the 3-rd index,
color 4 to the 4-th index.
Again, color 1 is assigned to 5-th index and color 2 to 6-th index.
Input: N = 20, M = 6, K = 3
Explanation: No such arrangement exists in which 6 colors may be assigned to at most 3 indices.
Approach: Observe the following points:
- If the number of colors is only 1 and the number of indices is greater than 1, then no such assignment can exist.
- If the total number of indices is greater than what can be colored by the colors available (M*K), then no such assignment exists.
Follow the steps below to solve the above problem:
- If the number of colors is 1 and the number of indices is greater than 1, then output -1.
- If the total number of colors is greater than what can be colored by the available colors (M*K), then output -1.
- If both of the above conditions do not meet, then:
- Initialize variable x with 1.
- Run a loop till N and within the loop, output x. Increment x and check if x is greater than M. If x becomes greater than M, set x = 1.
- When x is set to 1, the loop again starts printing the number of colors from 1.
Below is the implementation of the above approach:
1 2 3 4 1 2
Time Complexity: O(N)
Auxiliary Space: O(1)