Skip to problem
←

Graph Coloring with an Adjacency List

Medium 0 attempts

Given a simple undirected graph with n vertices and a positive integer m, decide whether every vertex can be assigned one of at most m colors so that adjacent vertices have different colors.

The input is an adjacency list: graph[v] contains the neighbors of vertex v. The graph has no self-loops or duplicate edges and may be disconnected. Colors can be reused across disconnected components; you do not need to use all m colors.

A triangle requires three colors because each vertex is adjacent to both others. A four-vertex cycle needs only two alternating colors. A graph with no edges needs just one color.

Function contract

Implement canColor(graph, m, n). graph has n rows; graph[v] lists the zero-based neighbors of vertex v. Every undirected edge appears in both endpoint lists. This input is an adjacency list, not a matrix.

Output: Return true if all vertices can be assigned at most m colors with different colors at every edge; otherwise return false.

Example 1

Input
graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
m = 3
n = 4
Output
true

Example 2

Input
graph = [[1,2],[0,2],[0,1]]
m = 2
n = 3
Output
false
Constraints
  • 1 <= n <= 20
  • 1 <= m <= n
  • graph is an adjacency list for a simple undirected graph with vertices 0 through n-1.

Approach: Backtracking

Assign colors to vertices one by one. For each vertex, try all m colors and check if any neighbor already has that color. If the assignment is safe, recurse to the next vertex. If no color works, backtrack.

javascript
function canColor(graph, m, n) {
  const colors = new Array(n).fill(0);

  function isSafe(node, color) {
    for (const neighbor of (graph[node] || [])) {
      if (colors[neighbor] === color) return false;
    }
    return true;
  }

  function solve(node) {
    if (node === n) return true;

    for (let c = 1; c <= m; c++) {
      if (isSafe(node, c)) {
        colors[node] = c;
        if (solve(node + 1)) return true;
        colors[node] = 0;
      }
    }
    return false;
  }

  return solve(0);
}

Time Complexity: O(n × m^n) worst case for m >= 2, including the neighbor scan for each attempted color. For m = 1, O(n + E), where E is the number of edges.

Space Complexity: O(n) for the color array and recursion stack

Loading discussion…

Saved in this browser only. Private to you.

JavaScript