M Coloring Problem

Recursion FAQs (Hard) Hard
  • The graph coloring problem is a critical concept in many real-world applications, such as register allocation in compilers, mobile radio frequency assignment, task scheduling and in Sudoku puzzles
  • For example, in register allocation during the compiling process, each register can be viewed as a color
  • The goal is to allocate the most efficiently without using the same register for intersecting live ranges of variables, similar to not coloring adjacent vertices with the same color in a graph
  • This graph-coloring method helps in writing efficient programs

Given an integer M and an undirected graph with N vertices and E edges. The goal is to determine whether the graph can be coloured with a maximum of M colors so that no two of its adjacent vertices have the same colour applied to them.


In this context, colouring a graph refers to giving each vertex a different colour. If the colouring of vertices is possible then return true, otherwise return false.

Examples:

Input : N = 4 , M = 3 , E = 5 , Edges = [ (0, 1) , (1, 2) , (2, 3) , (3, 0) , (0, 2) ]

Output : true

Explanation : Consider the three colors to be red, green, blue.

We can color the vertex 0 with red, vertex 1 with blue, vertex 2 with green, vertex 3 with blue.

In this way we can color graph using 3 colors at most.

Input : N = 3 , M = 2 , E = 3 , Edges = [ (0, 1) , (1, 2) , (0, 2) ]

Output : false

Explanation : Consider the three colors to be red, green.

We can color the vertex 0 with red, vertex 1 with blue.

As the vertex 2 is adjacent to both vertex 1 and 0 , so we cannot color with red and green.

Hence as we could not color all vertex of graph we return false.

Input : N = 5 , M = 3 , E = 5 , Edges = [ (0, 1) , (1, 2) , (0, 2) , (2,3) , (2,4) , (3,4) ]

Constraints

  • 1 <= N <= 20
  • 1 <= E <= (N*(N-1)/2)
  • 1 <= M <= N

Hints

  • This is a variation of the graph coloring problem, which is NP-complete. Start by attempting to color each vertex one by one. For each vertex, try assigning it a color from 1 to M.
  • "Use an adjacency list or adjacency matrix to represent the graph. For a vertex v, a color c is valid if no vertex adjacent to v is already colored withc. This can be implemented by iterating through the neighbors of v and checking their current colors."

Company Tags

Instacart Flipkart Bain & Company Rockstar Games Qualcomm Cerner KPMG eBay Swiggy Electronic Arts Philips Healthcare Broadcom GE Healthcare Salesforce Zomato ARM Medtronic Shopify Reddit Rakuten Seagate Technology Morgan Stanley McKinsey & Company PwC Western Digital Google Microsoft Amazon Meta Apple Netflix Adobe