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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code