Color Coding and Long Paths
-PATH asks whether a graph contains a simple path on vertices. For it is the Hamiltonian path problem, so it is NP-hard (Hamiltonian Cycles and the TSP). Brute force over sequences of distinct vertices costs about . Bounded search trees do not obviously help: there is no small obstruction to branch on. Color coding (Alon, Yuster and Zwick, 1995) solves it in time with a different idea: use randomness to turn "the vertices must be distinct" into a condition a dynamic program can check cheaply.
Colorful paths
The difficulty in a dynamic program for long paths is remembering which vertices have been used, which takes states. Instead, color every vertex with one of colors, uniformly and independently at random. A path is colorful if its vertices have different colors. A colorful path is automatically simple, and to extend it we only need to remember its set of colors, one of subsets:
The table has entries and each is computed by scanning a neighbourhood, so filling it takes time if subsets are processed in order of size. A colorful -path exists if is true for some .
How likely is the right path colorful? Fix one -path. Of the colorings of its vertices, use all colors, so
using . Repeating the experiment times with fresh colorings, the probability that the path is never colorful is at most ; repetitions push the failure probability below . The algorithm has one-sided error: a YES answer comes with a path and is always correct.
COLOR-CODING(G, k, rounds)
1 repeat rounds times
2 color each vertex uniformly from {1..k}
3 fill P(v, S) for all v and all color sets S, by increasing |S|
4 if P(v, all colors) for some v: return YES (and trace back the path)
5 return NO (wrong with probability at most (1 - k!/k^k)^rounds)Total time: for constant error probability.
Running it
The program first measures the probability that a fixed path is colorful, then runs color coding on random graphs, counting the colorings needed until the first success and checking the answer with an exhaustive depth-first search for simple paths.
import math
import random
rng = random.Random(1)
for k in [3, 5, 7, 9]:
hits = sum(len(set(rng.randrange(k) for _ in range(k))) == k for _ in range(20000))
print(f"k = {k}: colorful {hits / 20000:.4f} k!/k^k = {math.factorial(k) / k ** k:.4f} e^-k = {math.exp(-k):.4f}")k = 3: colorful 0.2220 k!/k^k = 0.2222 e^-k = 0.0498
k = 5: colorful 0.0408 k!/k^k = 0.0384 e^-k = 0.0067
k = 7: colorful 0.0053 k!/k^k = 0.0061 e^-k = 0.0009
k = 9: colorful 0.0006 k!/k^k = 0.0009 e^-k = 0.0001
import random
def colorful_path(adj, color, k):
n = len(adj)
full = (1 << k) - 1
reach = [dict() for _ in range(n)] # reach[v][S] = predecessor (or -1 for a start)
for v in range(n):
reach[v][1 << color[v]] = -1
for size in range(2, k + 1):
for v in range(n):
bit = 1 << color[v]
for u in adj[v]:
for S in list(reach[u]):
if bin(S).count("1") == size - 1 and not S & bit:
reach[v].setdefault(S | bit, u)
for v in range(n):
if full in reach[v]:
path, S = [v], full
while reach[v][S] != -1: # trace the path back
u = reach[v][S]
S ^= 1 << color[v]
v = u
path.append(v)
return path[::-1]
return None
def has_path_brute(adj, k):
def dfs(v, seen):
if len(seen) == k:
return True
return any(dfs(u, seen | {u}) for u in adj[v] if u not in seen)
return any(dfs(v, {v}) for v in range(len(adj)))
def graph(n, p, seed):
r = random.Random(seed)
adj = [[] for _ in range(n)]
for a in range(n):
for b in range(a + 1, n):
if r.random() < p:
adj[a].append(b); adj[b].append(a)
return adj
rng = random.Random(7)
print("seed k brute color coding colorings tried path")
for seed in range(4):
adj = graph(16, 0.13, seed)
for k in [6, 8]:
truth = has_path_brute(adj, k)
found, tries = None, 0
while found is None and tries < 300: # a fixed 8-path is missed with prob. ~0.49
tries += 1
color = [rng.randrange(k) for _ in range(16)]
found = colorful_path(adj, color, k)
ok = found is not None and len(set(found)) == k and all(b in adj[a] for a, b in zip(found, found[1:]))
print(f"{seed:4} {k:2} {str(truth):6} {str(found is not None):13} {tries:15} {found if ok else '-'}")seed k brute color coding colorings tried path
0 6 True True 32 [11, 14, 2, 9, 15, 10]
0 8 False False 300 -
1 6 True True 14 [5, 13, 1, 7, 4, 3]
1 8 False False 300 -
2 6 True True 24 [13, 15, 9, 8, 1, 7]
2 8 True False 300 -
3 6 True True 3 [1, 8, 9, 7, 6, 0]
3 8 True True 12 [14, 15, 11, 7, 6, 5, 9, 8]
On YES instances a colorful copy of some -path usually appears after a few dozen colorings, because a graph with one long path tends to have many. On NO instances every round fails and the algorithm gives up after its budget, correctly. The row for seed 2 and shows the one-sided error at work: an 8-path exists, but none was colorful in 300 rounds. That is no accident of bad luck in the code. For a single 8-path the chance of being colorful is , so 300 rounds miss it with probability about ; the rounds of the analysis, here about 3000, are needed for a constant success probability.
In C++
The dynamic program with color sets as bit masks: dp[S][v] is true if a colorful path with color set S ends at v. Masks are processed in increasing numeric order, which already puts every subset before its supersets.
#include <cstdio>
#include <vector>
int main() {
const int n = 40, k = 10;
std::vector<std::vector<int>> adj(n);
unsigned s = 17;
auto rnd = [&]() { s = s * 1103515245u + 12345u; return (s >> 16) & 0x7fff; };
for (int a = 0; a < n; a++)
for (int b = a + 1; b < n; b++)
if (rnd() % 100 < 5) { adj[a].push_back(b); adj[b].push_back(a); }
int full = (1 << k) - 1;
for (int round = 1; round <= 2000; round++) {
std::vector<int> color(n);
for (int v = 0; v < n; v++) color[v] = rnd() % k;
std::vector<std::vector<char>> dp(1 << k, std::vector<char>(n, 0));
for (int v = 0; v < n; v++) dp[1 << color[v]][v] = 1;
for (int S = 1; S <= full; S++)
for (int v = 0; v < n; v++) {
if (!dp[S][v]) continue;
for (int u : adj[v])
if (!(S >> color[u] & 1)) dp[S | 1 << color[u]][u] = 1;
}
for (int v = 0; v < n; v++)
if (dp[full][v]) {
std::printf("colorful %d-path ending at vertex %d found in round %d\n", k, v, round);
return 0;
}
}
std::printf("no %d-path found in 2000 rounds\n", k);
}colorful 10-path ending at vertex 12 found in round 12
Derandomization and faster algorithms
Derandomization (stated). A family of functions is -perfect if every -subset of is colored injectively by some function in the family. Trying every function of a -perfect family instead of random colorings makes the algorithm deterministic. Families of size exist and can be constructed in time linear in their size (Naor, Schulman and Srinivasan, 1995), so -PATH has a deterministic algorithm.
Faster algorithms (stated). Algebraic methods detect a multilinear monomial in a polynomial that encodes all walks: randomized for directed graphs (Koutis, 2008; Williams, 2009), and for undirected graphs (Björklund, Husfeldt, Kaski and Koivisto, 2010/2017). Deterministic algorithms reach about through representative sets (Fomin, Lokshtanov, Panolan and Saurabh, 2016).
Beyond paths. The same method finds any pattern graph on vertices of bounded treewidth inside in time, the original application of Alon, Yuster and Zwick. It does not help for -clique, where the pattern has treewidth and the problem is W[1]-hard (Parameterized Reductions and W[1]-Hardness).
Test yourself
Why does color coding only need to remember the set of colors used by a path, not its vertices?
- Because the graph is small
- Because a path whose vertices have pairwise different colors is automatically simple
- Because colors are chosen deterministically
- Because paths never revisit vertices
What is the probability that a fixed -path is colorful under a uniform random coloring with colors?
- , which is more than
What kind of error does color coding have?
- It can answer YES when there is no path
- One-sided: a YES answer comes with a real path; a NO answer can be wrong with probability that decreases exponentially in the number of rounds
- Two-sided with probability
- It never errs
How is color coding made deterministic?
- By using colors in round-robin order
- By trying every function of a -perfect hash family, which colors every -set injectively at least once
- By running the DP on all colorings
- It cannot be