TExcelTAD
Home › Randomized Algorithms & Probabilistic Analysis › Randomized 2-SAT: Papadimitriou's Walk

Randomized 2-SAT: Papadimitriou's Walk

A 2-CNF formula is a conjunction of clauses with two literals each, such as (x1∨¬x2)∧(x2∨x3)(x_1 \lor \lnot x_2) \land (x_2 \lor x_3). 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 O(n2)O(n^2) 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

text
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^-rounds

The 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 FF is satisfiable, the expected number of steps before WALK-2SAT finds a satisfying assignment is at most n2n^2.

Proof. Fix a satisfying assignment ss, and let XtX_t be the number of variables on which the current assignment agrees with ss after tt steps. When Xt=nX_t = n, the assignment is ss and the algorithm stops (it may stop earlier at a different satisfying assignment, which only helps).

Consider a step. The chosen clause CC is false under the current assignment but true under ss, so at least one of its two variables currently disagrees with ss. Flipping that variable increases XX by 1; flipping the other changes it by ±1\pm 1. So

Pr⁡[Xt+1=Xt+1]≥12,Pr⁡[Xt+1=Xt−1]≤12,\Pr[X_{t+1} = X_t + 1] \ge \frac12, \qquad \Pr[X_{t+1} = X_t - 1] \le \frac12 ,

whatever happened before. Compare XX with the walk YY on {0,…,n}\{0, \ldots, n\} that moves up or down with probability exactly 12\frac12 and always moves up from 0. Since XX is pushed upward at least as hard, its expected time to reach nn from any start is at most that of YY. (Formally, one couples the two processes so that Xt≥YtX_t \ge Y_t at all times; the details are in Mitzenmacher and Upfal, section 7.1.) For YY, first-step analysis gives the expected time hjh_j to reach nn from jj: with hn=0h_n = 0, h0=1+h1h_0 = 1 + h_1 and hj=1+12(hj−1+hj+1)h_j = 1 + \frac12(h_{j-1} + h_{j+1}), the solution is hj=n2−j2h_j = n^2 - j^2 (the mirror image of the calculation in Expectation Tricks: A Recap). So the expected time is at most h0=n2h_0 = n^2. □\square

Corollary. Running 2n22n^2 steps finds a satisfying assignment with probability at least 12\frac12, by Markov's inequality. Splitting 2kn22kn^2 steps into kk segments, each segment fails with probability at most 12\frac12 whatever its starting assignment (the theorem holds from any start), so all fail with probability at most 2−k2^{-k}.

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, (x0∨x0)∧(¬x0∨x1)∧(¬x1∨x2)∧⋯(x_0 \lor x_0) \land (\lnot x_0 \lor x_1) \land (\lnot x_1 \lor x_2) \land \cdots, 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.

python · try it yourself
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 nn steps, far below n2n^2. The chain is the worst case: each flip at the "frontier" of the true prefix moves it forward or backward with probability 12\frac12, 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 n2n^2: 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 2kn22kn^2 steps and answers "probably unsatisfiable". The program solves the first-step equations of the proof exactly (they give hj=n2−j2h_j = n^2 - j^2), then runs the walk with k=10k = 10 on a small unsatisfiable formula, and on a satisfiable one to show the contrast.

python · try it yourself
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 nn, with a fixed-seed std::mt19937 and incremental bookkeeping of violated clauses (only clauses containing the flipped variable can change), so each step costs O(1)O(1) amortized. The violated clause is again the first in index order, kept in a std::set.

cpp · try it yourself
#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 n2n^2: doubling nn quadruples the number of steps, the Θ(n2)\Theta(n^2) 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 ss, so a random flip helps with probability only ≥13\geq \frac13. The walk then drifts away from ss, and the expected time to hit it from distance jj grows like 2j2^j. 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 ss with probability at least 1/21/2?

  1. Because both variables disagree with ss
  2. Because the clause is true under ss and false now, so at least one of its two variables disagrees with ss
  3. Because ss is unique
  4. 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 nn variables?

  1. At most nn
  2. At most n2n^2
  3. At most 2n2^n
  4. At most nlog⁡nn \log n

What kind of error does WALK-2SAT have?

  1. It may report a non-satisfying assignment
  2. It may report "probably unsatisfiable" for a satisfiable formula
  3. Two-sided error
  4. No error at all

Why can the 2kn22kn^2 steps be split into kk independent-looking segments of 2n22n^2 steps?

  1. Because the walk restarts from all false
  2. Because the bound of n2n^2 expected steps holds from any starting assignment, so each segment succeeds with probability at least 1/21/2 given any history
  3. Because segments use different clauses
  4. Because Markov's inequality requires it