Randomized 2-SAT: Papadimitriou's Walk
A 2-CNF formula is a conjunction of clauses with two literals each, such as . Deciding whether it is satisfiable takes linear time with the implication graph and strongly connected components (Strongly Connected Components: Kosaraju's Algorithm, Satisfiability and SAT). Christos Papadimitriou (1991) found a strikingly different algorithm: start anywhere, and while some clause is false, flip a random variable of a false clause. It needs no graph algorithms at all, finds a satisfying assignment in expected steps, and its analysis is the prototype for using a random walk on a line to bound a local-search algorithm. The same idea with three literals per clause gives an exponential but nontrivial algorithm for 3-SAT (Schöning's Random Walk for 3-SAT).
The algorithm
WALK-2SAT(F, n, rounds) // F: 2-CNF formula on n variables
0 a = any assignment, e.g. all false
1 for step = 0 to 2 * rounds * n^2 - 1
2 if a satisfies F
3 return a // always correct
4 choose any clause C that a violates
5 choose one of the two variables of C uniformly at random and flip it in a
6 return "probably unsatisfiable" // wrong with probability at most 2^-roundsThe choice of the violated clause in line 4 can be arbitrary, even adversarial. If the formula is unsatisfiable the algorithm never finds an assignment, so the answer "satisfiable" (with a witness) is always correct; only "unsatisfiable" can be wrong. It is a Monte Carlo algorithm with one-sided error.
The analysis
Theorem (Papadimitriou, 1991). If is satisfiable, the expected number of steps before WALK-2SAT finds a satisfying assignment is at most .
Proof. Fix a satisfying assignment , and let be the number of variables on which the current assignment agrees with after steps. When , the assignment is and the algorithm stops (it may stop earlier at a different satisfying assignment, which only helps).
Consider a step. The chosen clause is false under the current assignment but true under , so at least one of its two variables currently disagrees with . Flipping that variable increases by 1; flipping the other changes it by . So
whatever happened before. Compare with the walk on that moves up or down with probability exactly and always moves up from 0. Since is pushed upward at least as hard, its expected time to reach from any start is at most that of . (Formally, one couples the two processes so that at all times; the details are in Mitzenmacher and Upfal, section 7.1.) For , first-step analysis gives the expected time to reach from : with , and , the solution is (the mirror image of the calculation in Expectation Tricks: A Recap). So the expected time is at most .
Corollary. Running steps finds a satisfying assignment with probability at least , by Markov's inequality. Splitting steps into segments, each segment fails with probability at most whatever its starting assignment (the theorem holds from any start), so all fail with probability at most .
Implementation
The program tests the walk on two families of satisfiable formulas: random 2-CNF formulas with a planted solution (every clause is chosen among those satisfied by a hidden assignment), and a chain, , whose only solution sets every variable true. Starting from all false, the chain forces a walk along the implications, and it is the hard case.
import random
def walk_2sat(n, clauses, rng, max_steps):
a = [False] * n
sat = lambda c: (a[c[0][0]] == c[0][1]) or (a[c[1][0]] == c[1][1]) # literal = (variable, value)
for step in range(max_steps):
bad = [c for c in clauses if not sat(c)]
if not bad:
return step, a
c = bad[0] # any violated clause: here the first one
v = c[rng.randrange(2)][0]
a[v] = not a[v]
return None, a
def planted(n, m, rng):
s = [rng.random() < 0.5 for _ in range(n)]
clauses = []
while len(clauses) < m:
u, v = rng.sample(range(n), 2)
c = ((u, rng.random() < 0.5), (v, rng.random() < 0.5))
if s[u] == c[0][1] or s[v] == c[1][1]: # keep only clauses that s satisfies
clauses.append(c)
return clauses
def chain(n):
return [((0, True), (0, True))] + [((i, False), (i + 1, True)) for i in range(n - 1)]
rng = random.Random(130)
print("instance n mean steps max steps n^2")
for name, make, n in [("planted, m = 2n", lambda n: planted(n, 2 * n, rng), 20),
("planted, m = 2n", lambda n: planted(n, 2 * n, rng), 40),
("chain", chain, 10), ("chain", chain, 20)]:
steps = []
for _ in range(40):
t, a = walk_2sat(n, make(n), rng, 10 * n * n)
steps.append(t)
print(f"{name:16} {n:4} {sum(steps) / len(steps):10.1f} {max(steps):9} {n * n:4}")instance n mean steps max steps n^2
planted, m = 2n 20 38.3 110 400
planted, m = 2n 40 74.6 187 1600
chain 10 92.1 492 100
chain 20 322.9 1066 400
Random planted formulas are easy: most clauses are satisfied by many assignments, and the walk finds one within a few times steps, far below . The chain is the worst case: each flip at the "frontier" of the true prefix moves it forward or backward with probability , an honest unbiased random walk. In fact the agreement with the solution performs exactly the reflected walk of the proof, so the expected number of steps is exactly : the bound is tight, and the sample means scatter around it (a hitting time has a standard deviation comparable to its mean).
Giving up on an unsatisfiable formula
On an unsatisfiable formula the walk never succeeds, so the algorithm runs its full budget of steps and answers "probably unsatisfiable". The program solves the first-step equations of the proof exactly (they give ), then runs the walk with on a small unsatisfiable formula, and on a satisfiable one to show the contrast.
import random
from fractions import Fraction
def hitting_times(n):
# h_n = 0, h_0 = 1 + h_1, h_j = 1 + (h_{j-1} + h_{j+1}) / 2; differences d_j = h_{j-1} - h_j
d = [Fraction(0)] * (n + 1)
d[1] = Fraction(1) # from h_0 = 1 + h_1
for j in range(1, n):
d[j + 1] = d[j] + 2 # from the middle equation
h = [sum(d[1:], Fraction(0))]
for j in range(1, n + 1):
h.append(h[-1] - d[j])
return h
n = 6
print("h_j:", [int(x) for x in hitting_times(n)], " n^2 - j^2:", [n * n - j * j for j in range(n + 1)])
def walk(n, clauses, rng, steps):
a = [False] * n
for t in range(steps):
bad = next((c for c in clauses if not any(a[v] == w for v, w in c)), None)
if bad is None:
return f"satisfiable after {t} steps: {a}"
v = bad[rng.randrange(2)][0]
a[v] = not a[v]
return f"probably unsatisfiable after {steps} steps"
# x0 or x1, x0 or not x1, not x0 or x1, not x0 or not x1: every assignment violates one clause
unsat = [((0, True), (1, True)), ((0, True), (1, False)), ((0, False), (1, True)), ((0, False), (1, False))]
sat = unsat[:3]
rng = random.Random(131)
k = 10
print("unsatisfiable:", walk(2, unsat, rng, 2 * k * 2 ** 2))
print("satisfiable: ", walk(2, sat, rng, 2 * k * 2 ** 2))h_j: [36, 35, 32, 27, 20, 11, 0] n^2 - j^2: [36, 35, 32, 27, 20, 11, 0]
unsatisfiable: probably unsatisfiable after 80 steps
satisfiable: satisfiable after 4 steps: [True, True]
In C++
The walk in C++ on the chain for larger , with a fixed-seed std::mt19937 and incremental bookkeeping of violated clauses (only clauses containing the flipped variable can change), so each step costs amortized. The violated clause is again the first in index order, kept in a std::set.
#include <cstdio>
#include <random>
#include <set>
#include <vector>
struct Lit { int var; bool val; };
struct Clause { Lit a, b; };
long long walk(int n, const std::vector<Clause>& f, std::mt19937& rng) {
std::vector<bool> x(n, false);
std::vector<std::vector<int>> occ(n);
for (int i = 0; i < (int)f.size(); ++i) { occ[f[i].a.var].push_back(i); occ[f[i].b.var].push_back(i); }
auto sat = [&](int i) { return x[f[i].a.var] == f[i].a.val || x[f[i].b.var] == f[i].b.val; };
std::set<int> bad;
for (int i = 0; i < (int)f.size(); ++i) if (!sat(i)) bad.insert(i);
long long steps = 0;
while (!bad.empty()) {
const Clause& c = f[*bad.begin()];
int v = (rng() & 1) ? c.a.var : c.b.var;
x[v] = !x[v];
++steps;
for (int i : occ[v]) { if (sat(i)) bad.erase(i); else bad.insert(i); }
}
return steps;
}
int main() {
std::mt19937 rng(130);
std::printf(" n mean steps over 200 runs n^2\n");
for (int n : {25, 50, 100, 200}) {
std::vector<Clause> f{{{0, true}, {0, true}}};
for (int i = 0; i + 1 < n; ++i) f.push_back({{i, false}, {i + 1, true}});
long long total = 0;
for (int r = 0; r < 200; ++r) total += walk(n, f, rng);
std::printf("%4d %24.1f %5d\n", n, total / 200.0, n * n);
}
} n mean steps over 200 runs n^2
25 639.2 625
50 2591.4 2500
100 9391.4 10000
200 37290.1 40000
The means stay close to : doubling quadruples the number of steps, the behaviour of an unbiased walk.
Why it does not extend directly to 3-SAT
For a violated 3-clause, at least one of three variables disagrees with , so a random flip helps with probability only . The walk then drifts away from , and the expected time to hit it from distance grows like . Schöning's idea is to accept that and restart often from fresh random assignments; that is the next lesson.
Test yourself
Why does flipping a random variable of a violated 2-clause move towards a fixed satisfying assignment with probability at least ?
- Because both variables disagree with
- Because the clause is true under and false now, so at least one of its two variables disagrees with
- Because is unique
- Because the clause was chosen at random
What is the expected number of steps of Papadimitriou's walk on a satisfiable 2-CNF formula with variables?
- At most
- At most
- At most
- At most
What kind of error does WALK-2SAT have?
- It may report a non-satisfying assignment
- It may report "probably unsatisfiable" for a satisfiable formula
- Two-sided error
- No error at all
Why can the steps be split into independent-looking segments of steps?
- Because the walk restarts from all false
- Because the bound of expected steps holds from any starting assignment, so each segment succeeds with probability at least given any history
- Because segments use different clauses
- Because Markov's inequality requires it