TExcelTAD
Home › Parameterized & Fine-Grained Complexity › Color Coding and Long Paths

Color Coding and Long Paths

kk-PATH asks whether a graph contains a simple path on kk vertices. For k=nk = n it is the Hamiltonian path problem, so it is NP-hard (Hamiltonian Cycles and the TSP). Brute force over sequences of kk distinct vertices costs about nkn^k. 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 2O(k)⋅m2^{O(k)} \cdot m 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 (nk)\binom{n}{k} states. Instead, color every vertex with one of kk colors, uniformly and independently at random. A path is colorful if its kk vertices have kk different colors. A colorful path is automatically simple, and to extend it we only need to remember its set of colors, one of 2k2^k subsets:

P(v,S)=true  ⟺  some colorful path ending at v uses exactly the colors in S.P(v, S) = \text{true} \iff \text{some colorful path ending at } v \text{ uses exactly the colors in } S.
P(v,{c(v)})=true,P(v,S)=⋁u∈N(v)P(u,S∖{c(v)})when c(v)∈S.P(v, \{c(v)\}) = \text{true}, \qquad P(v, S) = \bigvee_{u \in N(v)} P(u, S \setminus \{c(v)\}) \quad \text{when } c(v) \in S.

The table has 2kn2^k n entries and each is computed by scanning a neighbourhood, so filling it takes O(2k⋅k⋅m)O(2^k \cdot k \cdot m) time if subsets are processed in order of size. A colorful kk-path exists if P(v,[k])P(v, [k]) is true for some vv.

How likely is the right path colorful? Fix one kk-path. Of the kkk^k colorings of its vertices, k!k! use all colors, so

Pr⁡[colorful]=k!kk>e−k,\Pr[\text{colorful}] = \frac{k!}{k^k} > e^{-k},

using k!>(k/e)kk! > (k/e)^k. Repeating the experiment eke^k times with fresh colorings, the probability that the path is never colorful is at most (1−e−k)ek<1e(1 - e^{-k})^{e^k} < \frac{1}{e}; t⋅ekt \cdot e^k repetitions push the failure probability below e−te^{-t}. The algorithm has one-sided error: a YES answer comes with a path and is always correct.

text
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: O(ek⋅2k⋅k⋅m)=O((2e)k⋅km)O(e^k \cdot 2^k \cdot k \cdot m) = O((2e)^k \cdot k m) 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.

python · try it yourself
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
python · try it yourself
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 kk-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 k=8k = 8 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 8!88≈0.0024\frac{8!}{8^8} \approx 0.0024, so 300 rounds miss it with probability about (1−0.0024)300≈0.49(1 - 0.0024)^{300} \approx 0.49; the eke^k 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.

cpp · try it yourself
#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 F\mathcal{F} of functions V→[k]V \to [k] is kk-perfect if every kk-subset of VV is colored injectively by some function in the family. Trying every function of a kk-perfect family instead of random colorings makes the algorithm deterministic. Families of size ekkO(log⁡k)log⁡ne^{k} k^{O(\log k)} \log n exist and can be constructed in time linear in their size (Naor, Schulman and Srinivasan, 1995), so kk-PATH has a deterministic 2O(k)⋅mlog⁡n2^{O(k)} \cdot m \log n algorithm.

Faster algorithms (stated). Algebraic methods detect a multilinear monomial in a polynomial that encodes all walks: O∗(2k)O^*(2^k) randomized for directed graphs (Koutis, 2008; Williams, 2009), and O∗(1.66k)O^*(1.66^k) for undirected graphs (Björklund, Husfeldt, Kaski and Koivisto, 2010/2017). Deterministic algorithms reach about O∗(2.6k)O^*(2.6^k) through representative sets (Fomin, Lokshtanov, Panolan and Saurabh, 2016).

Beyond paths. The same method finds any pattern graph HH on kk vertices of bounded treewidth inside GG in 2O(k)nO(1)2^{O(k)} n^{O(1)} time, the original application of Alon, Yuster and Zwick. It does not help for kk-clique, where the pattern has treewidth k−1k - 1 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?

  1. Because the graph is small
  2. Because a path whose vertices have pairwise different colors is automatically simple
  3. Because colors are chosen deterministically
  4. Because paths never revisit vertices

What is the probability that a fixed kk-path is colorful under a uniform random coloring with kk colors?

  1. 1k\frac{1}{k}
  2. k!kk\frac{k!}{k^k}, which is more than e−ke^{-k}
  3. 2−k2^{-k}
  4. 12\frac{1}{2}

What kind of error does color coding have?

  1. It can answer YES when there is no path
  2. 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
  3. Two-sided with probability 12\frac{1}{2}
  4. It never errs

How is color coding made deterministic?

  1. By using kk colors in round-robin order
  2. By trying every function of a kk-perfect hash family, which colors every kk-set injectively at least once
  3. By running the DP on all knk^n colorings
  4. It cannot be