M-Coloring Problem

medium

You are given an undirected graph with V vertices (labeled 0 to V-1) and E edges, described by a list edges where each entry [u, v] is an undirected edge between vertices u and v. You are also given an integer m, the number of available colors.

Decide whether you can assign a color to every vertex — using at most m colors — so that no edge connects two vertices of the same color. Return true if such a coloring exists, and false otherwise.

You do not have to use all m colors; m is only an upper bound. The graph uses 0-based vertex labels.

Hints

You're handing out colors to vertices so that no edge has both ends the same. What's the smallest decision you make at each step?
You don't need to finish a full coloring to know it's doomed. Reject a color the instant it clashes with an already-colored neighbor.
Assign colors one vertex at a time, only picking a color that's safe; if a vertex has no safe color, backtrack and recolor the previous vertex.

Common doubts

No. m is an upper bound — using fewer is fine. You only need a valid coloring with at most m colors.
No. Disconnected components are colored independently, and the same backtracking handles them without any extra code.
Under these constraints, no. A self-loop would make a vertex adjacent to itself and thus impossible to color. Treat the input as a simple undirected graph.

Interview follow-ups

That's the chromatic number — find the smallest m for which the answer is true, e.g. by trying m = 1, 2, 3, … until it succeeds.
Order vertices most-constrained-first (highest degree), break symmetry by fixing vertex 0 to color 1, or add forward checking to prune earlier.

Fun facts

  • Any planar graph — think of a flat map of countries — needs at most 4 colors. That's the famous Four Color Theorem.
  • Graph coloring is how compilers assign CPU registers and how exam timetables avoid clashes: the 'colors' become registers or time slots.

Asked at

AmazonGoogleMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: V = 4, edges = [[0,1],[1,3],[2,3],[3,0],[0,2]], m = 3
Output: true
One valid coloring with 3 colors: 0->1, 1->2, 2->2, 3->3. Every edge joins two different colors.
Example 2
Input: V = 3, edges = [[0,1],[1,2],[0,2]], m = 2
Output: false
Vertices 0, 1, 2 form a triangle where all three are mutually adjacent, so they need 3 distinct colors — 2 is not enough.
Constraints

- 1 <= V <= 10 - 1 <= E <= V*(V-1)/2 - 0 <= edges[i][0], edges[i][1] <= V-1 - 1 <= m <= V

Solve this problem →