Graph Coloring - Problem

Given an undirected graph represented as an adjacency list, color the vertices using the minimum number of colors such that no two adjacent vertices share the same color.

This is a classic Graph Coloring Problem which is NP-hard in general, but can be solved optimally for small graphs using backtracking.

Input: An adjacency list representation where graph[i] contains all neighbors of vertex i.

Output: An array where result[i] is the color assigned to vertex i. Colors are represented as integers starting from 0.

Goal: Use the minimum possible number of colors while ensuring no adjacent vertices have the same color.

Input & Output

Example 1 — Square Graph (4-Cycle)
$ Input: graph = [[1,2],[0,3],[0,3],[1,2]]
Output: [0,1,2,0]
💡 Note: This is a square/cycle graph with 4 vertices. Vertices 0 and 2 are not adjacent, so they can share color 0. Vertices 1 and 3 are not adjacent, but 1 needs color 1 (can't use 0 like vertex 0), and vertex 3 can use color 0 (not adjacent to vertex 0). Minimum colors needed: 3.
Example 2 — Triangle Graph
$ Input: graph = [[1,2],[0,2],[0,1]]
Output: [0,1,2]
💡 Note: This is a complete triangle where every vertex is connected to every other vertex. Each vertex needs a unique color, so we need 3 colors: vertex 0 gets color 0, vertex 1 gets color 1, vertex 2 gets color 2.
Example 3 — Disconnected Components
$ Input: graph = [[1],[0],[3],[2]]
Output: [0,1,0,1]
💡 Note: Two separate edges: 0-1 and 2-3. Since components don't connect, we can reuse colors. Vertices 0 and 2 both get color 0, vertices 1 and 3 both get color 1. Only 2 colors needed.

Constraints

  • 1 ≤ graph.length ≤ 20
  • 0 ≤ graph[i].length ≤ 19
  • graph[i][j] is a valid vertex index
  • graph[i] does not contain i (no self-loops)
  • graph[i] contains no duplicate values

Visualization

Tap to expand
INPUT GRAPHALGORITHM STEPSFINAL RESULT0123Adjacency List:[[1,2],[0,3],[0,3],[1,2]]Square/Cycle Graph4 vertices, 4 edges1Color vertex 0 → Red (0)2Color vertex 1 → Blue (1)3Color vertex 2 → Green (2)4Color vertex 3 → Red (0)Backtracking ensures noadjacent vertices share colors3 colors needed minimum0123[0,1,2,0]Valid 3-coloring found!No adjacent verticesshare the same color-->-->Key Insight:Graph coloring uses backtracking to assign minimum colors while ensuringno adjacent vertices share the same color - like painting countries on a map!TutorialsPoint - Graph Coloring | Backtracking with Pruning
Asked in
Google 25 Microsoft 18 Facebook 15 Amazon 12
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen