Algorithms · Visualized

M-Coloring Problem

Backtracking

Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.

Given a graph and m colors, assign each vertex a color so that no two adjacent vertices share one. Time: O(mⁿ) average, O(mⁿ) — n vertices, m choices each worst; space: O(n) recursion depth plus the color array.

Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.

M-Coloring Problem

Backtracking

Given a graph and m colors, assign each vertex a color so that no two adjacent vertices share one. Backtracking colors vertices in order: try color 1..m on the current vertex, skip any color used by an already-colored neighbour, recurse to the next vertex, and backtrack when every color is blocked.

How M-Coloring Problem Works

  1. Start with vertex 0 and no colors assigned.
  2. For the current vertex, try each color from 1 to m.
  3. Check every already-colored neighbour: if any uses this color, reject it.
  4. If a color survives, assign it and recurse on the next vertex.
  5. If all vertices are colored, a valid coloring has been found; if a vertex runs out of colors, undo (backtrack) and let an earlier vertex try its next color.

M-Coloring Problem Worked Example

Input: {graph: [[1, 2], [0, 2, 3], [0, 1, 3], [1, 2]], m: 3}

Vertex 0 → c1. Vertex 1 (adjacent to 0) → c2. Vertex 2 (adjacent to both) → c3. Vertex 3 (adjacent to 1 and 2): c1 free → assign. Result: [c1, c2, c3, c1] — only 3 colors needed for this cycle-plus-chord graph.

M-Coloring ProblemO(mⁿ)
Color every vertex so adjacent vertices differ, using at most m colors.
0
0
0
1
0
2
0
3
vertexcolorneighbours
00—1, 2
11—0, 2, 3
22—0, 1, 3
33—1, 2
m3
Step 1 / 9
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Graph M-Coloring: color every vertex with one of 3 colors — adjacent vertices must differ.
Python · Backtracking in Code
def m_coloring(graph, m):
    n = len(graph)
    color = [0] * n

    def safe(v, c):
        return all(color[nb] != c for nb in graph[v])

    def rec(v):
        if v == n:
            return True
        for c in range(1, m + 1):
            if safe(v, c):
                color[v] = c
                if rec(v + 1):
                    return True
                color[v] = 0        # backtrack
        return False

    return color if rec(0) else None

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

M-Coloring Problem Time & Space Complexity

BestO(mⁿ) with heavy pruning
AverageO(mⁿ)
WorstO(mⁿ) — n vertices, m choices each
SpaceO(n) recursion depth plus the color array

When to Use M-Coloring Problem

  • Timetabling / exam scheduling where clashing events need different slots.
  • Register allocation in compilers (variables that are live simultaneously get different registers).
  • Map coloring — the classic application that gave the problem its name.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.