Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

2-SAT

Boolean formulas with two-literal clauses, solved through implication graphs.

Allow three literals per clause and satisfiability is NP-complete, the problem on which the whole theory of NP-completeness was founded. Allow only two and it collapses into reachability: a directed graph on the literals, one strongly connected components computation, linear time. This lesson proves the collapse and shows how far it reaches.

What you’ll learn

  • Build the implication graph of a 2-CNF formula and use its skew symmetry: u⇝vu \rightsquigarrow v if and only if ¬v⇝¬u\lnot v \rightsquigarrow \lnot u.
  • Prove that a 2-CNF formula is satisfiable exactly when no variable shares a strongly connected component with its negation, and extract a satisfying assignment from a topological order of the components.
  • Implement 2-SAT in O(n+m)O(n + m) and encode binary choices with pairwise constraints, including "at most one" with linearly many clauses.
  • Place 2-SAT among its relatives: 3-SAT, MAX-2-SAT, model counting, NL-completeness, random walks and Schaefer's dichotomy.

From clauses to implications

A clause (a∨b)(a \lor b) fails only when both of its literals are false. So if aa is false then bb must be true, and if bb is false then aa must be true:

(a∨b)  ≡  (¬a⇒b)∧(¬b⇒a)(a \lor b) \;\equiv\; (\lnot a \Rightarrow b) \land (\lnot b \Rightarrow a)
The implication graph has one vertex per literal, 2n2n in all, and these two edges for every clause, 2m2m in all.

The graph is skew-symmetric: the two edges of a clause are contrapositives of each other, so u→vu \to v is an edge exactly when ¬v→¬u\lnot v \to \lnot u is. Reading a path backward and negating every literal gives another path: u⇝vu \rightsquigarrow v if and only if ¬v⇝¬u\lnot v \rightsquigarrow \lnot u. In particular, the strongly connected components come in mirror pairs CC and ¬C={¬ℓ:ℓ∈C}\lnot C = \{\lnot \ell : \ell \in C\}.

Check your understanding

Which single clause, added to FF, makes it unsatisfiable?

  1. (a∨d)(a \lor d)
  2. (¬a∨¬b)(\lnot a \lor \lnot b)
  3. (b∨¬d)(b \lor \lnot d)
  4. (¬c∨d)(\lnot c \lor d)
Show the answer

D. (¬c∨d)(\lnot c \lor d)

FF forces cc true and then dd false, while (¬c∨d)(\lnot c \lor d) demands dd true whenever cc is. In the graph, its edge c→dc \to d closes the cycle c→d→¬c→¬a→b→cc \to d \to \lnot c \to \lnot a \to b \to c, which puts cc and ¬c\lnot c in one component.

The component criterion

DerivationProof
  1. u⇝v  ⟹  (u⇒v) holds in every modelu \rightsquigarrow v \;\Longrightarrow\; (u \Rightarrow v) \text{ holds in every model}

    Edges are sound implications. A model that satisfies (a∨b)(a \lor b) and makes ¬a\lnot a true makes bb true. So truth flows along every path:

  2. x⇝¬x  and  ¬x⇝x  ⟹  no modelx \rightsquigarrow \lnot x \ \text{ and } \ \lnot x \rightsquigarrow x \;\Longrightarrow\; \text{no model}

    Necessity. If xx and ¬x\lnot x share a component, then x⇝¬xx \rightsquigarrow \lnot x and ¬x⇝x\lnot x \rightsquigarrow x. A model with xx true makes ¬x\lnot x true, and a model with xx false makes xx true; both are impossible:

  3. τ(a)<τ(¬a)≤τ(b)<τ(¬b)≤τ(a),a contradiction.\tau(a) < \tau(\lnot a) \le \tau(b) < \tau(\lnot b) \le \tau(a),\quad\text{a contradiction.}

    Sufficiency. If xx and ¬x\lnot x always lie in different components, then τ(x)≠τ(¬x)\tau(x) \ne \tau(\lnot x), so the rule makes exactly one of them true. Suppose a clause (a∨b)(a \lor b) ended up with both literals false: τ(a)<τ(¬a)\tau(a) < \tau(\lnot a) and τ(b)<τ(¬b)\tau(b) < \tau(\lnot b). Its edges ¬a→b\lnot a \to b and ¬b→a\lnot b \to a point forward or within a component, so τ(¬a)≤τ(b)\tau(\lnot a) \le \tau(b) and τ(¬b)≤τ(a)\tau(\lnot b) \le \tau(a). Chaining:

  4. O(n+m)O(n + m)

    Cost. One strongly connected components computation on 2n2n vertices and 2m2m edges, then one scan over the variables:

Tarjan's algorithm numbers components in reverse topological order, so the rule becomes "xx is true if and only if comp[x]<comp[¬x]\text{comp}[x] < \text{comp}[\lnot x]"; with Kosaraju's numbering, sources first, the comparison flips.

python
def two_sat(n, clauses, scc):
    """clauses: pairs (a, b) of literals; +i is x_i and -i is not x_i (i = 1..n).
    scc(N, adj) must number components in reverse topological order, like tarjan().
    Returns a satisfying list of n booleans, or None if the formula is unsatisfiable."""
    node = lambda lit: 2 * (abs(lit) - 1) + (lit < 0)   # x_i -> 2i-2, not x_i -> 2i-1
    adj = [[] for _ in range(2 * n)]
    for a, b in clauses:                 # (a or b) == (not a -> b) and (not b -> a)
        adj[node(-a)].append(node(b))
        adj[node(-b)].append(node(a))
    comp = scc(2 * n, adj)
    if any(comp[2 * i] == comp[2 * i + 1] for i in range(n)):
        return None                      # x and not x share a component
    # x_i is true iff its component comes later in topological order (smaller Tarjan id)
    return [comp[2 * i] < comp[2 * i + 1] for i in range(n)]

Pass the tarjan function from the lesson on strongly connected components as scc. On FF, with a,b,c,da, b, c, d numbered 11 to 44, the call two_sat(4, [(1, 2), (-1, 3), (-2, 3), (-3, -4)], tarjan) returns a=b=c=truea = b = c = \text{true}, d=falsed = \text{false}. Another topological order can yield another model, and every model produced this way is valid.

Think first Why not simply fix the variables one at a time, choosing each value arbitrarily?

Arbitrary choices can conflict: setting aa and bb both false before looking at (a∨b)(a \lor b) breaks that clause. Choices work if each is propagated before the next is made: set xx, make true everything reachable from the chosen literal, and back off if that reaches a contradiction. Propagating tentative choices is the idea behind the polynomial-time algorithm of Even, Itai and Shamir (1976). The topological rule makes all the choices at once, consistently, in linear time.

Modeling with two literals

2-SAT fits when every object makes one binary choice and every constraint mentions at most two of those choices. Each constraint becomes one or two clauses:

ConstraintClauses
xx must hold(x∨x)(x \lor x)
if xx then yy(¬x∨y)(\lnot x \lor y)
xx or yy(x∨y)(x \lor y)
not both xx and yy(¬x∨¬y)(\lnot x \lor \lnot y)
x=yx = y(¬x∨y)(\lnot x \lor y) and (x∨¬y)(x \lor \lnot y)
x≠yx \ne y (exactly one)(x∨y)(x \lor y) and (¬x∨¬y)(\lnot x \lor \lnot y)
at most one of x1,…,xkx_1, \dots, x_k(k2)\binom{k}{2} clauses (¬xi∨¬xj)(\lnot x_i \lor \lnot x_j), or 3k−23k - 2 clauses with prefix variables
A problem made only of x=yx = y and x≠yx \ne y constraints is two-coloring, which BFS already solves; 2-SAT mixes such constraints freely with implications and fixed values.

"At most one" in linear size. Introduce pip_i, meaning "some of x1,…,xix_1, \dots, x_i is true", with the clauses xi⇒pix_i \Rightarrow p_i, pi−1⇒pip_{i-1} \Rightarrow p_i and pi−1⇒¬xip_{i-1} \Rightarrow \lnot x_i. If xix_i and xjx_j with i<ji < j were both true, the chain xi⇒pi⇒⋯⇒pj−1⇒¬xjx_i \Rightarrow p_i \Rightarrow \cdots \Rightarrow p_{j-1} \Rightarrow \lnot x_j would fail. With at most one true variable, setting each pip_i to its intended meaning satisfies every clause. That is 3k−23k - 2 clauses instead of k(k−1)/2k(k-1)/2.

Problem (in our words)The binary choiceThe clauses
Each guest names two wishes, such as "invite Ana" or "do not invite Ben"; choose whom to invite so that every guest gets at least one wishinvite each person or notone clause (w1∨w2)(w_1 \lor w_2) per guest
Each map label sits above or below its point, and two overlapping label positions cannot both be usedthe position of each label(¬p∨¬q)(\lnot p \lor \lnot q) for every overlapping pair
Each of nn flags goes at one of two given spots; maximize the smallest distance between two flagsthe spot of each flagbinary search on the distance DD: every pair of spots closer than DD gives a "not both" clause, and each test is a 2-SAT instance with O(n2)O(n^2) clauses
Workshops run in the morning or the afternoon; some pairs share a speaker and need different slots, some must run together, some are fixedthe slot of each workshopx≠yx \ne y, x=yx = y and one-literal clauses
The third row is a common contest pattern: binary search on the answer around a 2-SAT feasibility test.
Check your understanding

Which of these problems reduces to 2-SAT?

  1. Color every country on a map red, green or blue so that neighbors differ
  2. Each workshop runs in the morning or the afternoon; some pairs share a speaker and need different slots, some pairs must run in the same slot, and if workshop AA runs in the afternoon then so does workshop BB
  3. Choose the fewest servers so that every client is next to a chosen server
  4. Satisfy as many as possible of a list of constraints of the form "xx or yy"
Show the answer

B. Each workshop runs in the morning or the afternoon; some pairs share a speaker and need different slots, some pairs must run in the same slot, and if workshop AA runs in the afternoon then so does workshop BB

One Boolean variable per workshop (true for morning). "Different slots" is x≠yx \ne y, "same slot" is x=yx = y, and "if AA is in the afternoon then so is BB" is ¬a⇒¬b\lnot a \Rightarrow \lnot b, the clause (a∨¬b)(a \lor \lnot b). Every constraint has two literals, so the implication graph decides it in linear time.

Where 2-SAT sits

Krom (1967) studied 2-CNF formulas in logic; Even, Itai and Shamir (1976) gave a polynomial-time algorithm in a paper proving timetabling NP-complete; and Aspvall, Plass and Tarjan (1979) gave the linear-time component algorithm, which, as their title says, also decides quantified 2-CNF formulas in linear time. Around the decision problem, everything else is hard:

ProblemComplexity
2-SATO(n+m)O(n + m); NL-complete: its complement is NL-complete (Jones, Lien & Laaser, 1976), and NL is closed under complement (Immerman; Szelepcsényi)
Quantified 2-CNF formulasO(n+m)O(n + m) (Aspvall, Plass & Tarjan, 1979)
3-SATNP-complete (Cook, 1971)
MAX-2-SATNP-hard (Garey, Johnson & Stockmeyer, 1976); approximable within a factor of about 0.9400.940 (Lewin, Livnat & Zwick), which is optimal if the Unique Games Conjecture holds (Austrin; Brakensiek, Huang & Zwick)
#\#2-SAT: counting the models#P\#\mathrm{P}-complete, even for formulas without negations (Valiant, 1979)
Deciding whether a model exists is easy; how many models there are, or how many clauses can hold at best, is not.
DerivationProof sketch
  1. Pr⁡[X→X+1]≥12,Pr⁡[X→X−1]≤12\Pr[X \to X + 1] \ge \tfrac12, \qquad \Pr[X \to X - 1] \le \tfrac12

    Fix a model A∗A^{*} and let XX count the variables on which the current assignment agrees with A∗A^{*}. A false clause has both literals false, but A∗A^{*} makes one of them true, so at least one of its two variables disagrees with A∗A^{*}. A random flip of one of the two therefore raises XX with probability at least 12\tfrac12:

  2. hj=n2−j2≤n2h_j = n^2 - j^2 \le n^2

    For the unbiased walk on {0,…,n}\{0, \dots, n\}, reflected at 00, let hjh_j be the expected number of steps to reach nn from jj. Then hn=0h_n = 0, h0=1+h1h_0 = 1 + h_1 and hj=1+12(hj−1+hj+1)h_j = 1 + \tfrac12(h_{j-1} + h_{j+1}), solved by

  3. Pr⁡[no model within 2n2 flips]≤12\Pr[\text{no model within } 2n^2 \text{ flips}] \le \tfrac12

    A walk pushed upward at least as often reaches nn no later in expectation, and it may stop earlier at another model. By Markov's inequality, 2n22n^2 flips succeed with probability at least 12\tfrac12, and repeating the walk drives the failure probability down exponentially:

Schöning (1999) ran the same walk, with random restarts, on 3-CNF formulas and obtained an O∗((4/3)n)O^{*}\big((4/3)^n\big)-time algorithm for 3-SAT, a landmark of exact exponential algorithms.

Schaefer's dichotomy (1978). Consider satisfiability for formulas built from any fixed finite set of Boolean constraint types. Schaefer proved that the problem is in P if all constraints are satisfied by the all-false assignment, or all by the all-true assignment, or all are Horn, or all dual-Horn, or all bijunctive (expressible in 2-CNF), or all affine (systems of XOR equations), and NP-complete in every other case. 2-SAT is the bijunctive island. In 2017 Bulatov and, independently, Zhuk proved the corresponding dichotomy for constraint satisfaction over every finite domain, settling the Feder–Vardi conjecture.

Key takeaways

  • A clause (a∨b)(a \lor b) is the pair of implications ¬a⇒b\lnot a \Rightarrow b and ¬b⇒a\lnot b \Rightarrow a; the implication graph on 2n2n literals is skew-symmetric: u⇝vu \rightsquigarrow v if and only if ¬v⇝¬u\lnot v \rightsquigarrow \lnot u.
  • A 2-CNF formula is satisfiable if and only if no xx shares a component with ¬x\lnot x; then making xx true when its component comes after ¬x\lnot x's in topological order satisfies it, all in O(n+m)O(n + m) (Aspvall, Plass & Tarjan, 1979).
  • 2-SAT models binary choices with pairwise constraints: implications, equalities, exclusions, "at most one" with 3k−23k - 2 clauses, and binary search on an answer with a 2-SAT feasibility test.
  • The boundary is sharp: 3-SAT is NP-complete, MAX-2-SAT NP-hard and counting 2-SAT models #P-complete, while 2-SAT itself is NL-complete and one of Schaefer's tractable classes.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the implication graph of a 2-CNF formula there is a path from literal uu to literal vv. Which other path must exist?

  1. From vv to uu
  2. From ¬u\lnot u to ¬v\lnot v
  3. From ¬v\lnot v to ¬u\lnot u
  4. From uu to ¬v\lnot v
Show the answer

C. From ¬v\lnot v to ¬u\lnot u

Each clause contributes an edge and its contrapositive, so reversing a path and negating its literals gives a path: u⇝vu \rightsquigarrow v implies ¬v⇝¬u\lnot v \rightsquigarrow \lnot u. This is the contrapositive of "uu implies vv".

Question 2

Tarjan's algorithm on an implication graph gives comp[x]=3\text{comp}[x] = 3 and comp[¬x]=7\text{comp}[\lnot x] = 7. What value does the standard rule give xx?

  1. True: Tarjan numbers components sinks first, so xx's component comes later in topological order
  2. False: xx's component has the smaller number
  3. Either value: since the components differ, xx is unconstrained
  4. Nothing yet: the formula may still be unsatisfiable
Show the answer

A. True: Tarjan numbers components sinks first, so xx's component comes later in topological order

Smaller Tarjan numbers come later in topological order, so τ(¬x)<τ(x)\tau(\lnot x) < \tau(x) and the rule makes xx true. Intuitively, a literal late in the order implies little, so making it true is safe.

Question 3

Which of these problems is NP-hard?

  1. Deciding whether a 2-CNF formula is satisfiable
  2. Deciding a quantified 2-CNF formula such as ∀x ∃y ∀z  φ\forall x\, \exists y\, \forall z\; \varphi
  3. Deciding whether a 2-CNF formula whose clauses all have the form (xi∨¬xj)(x_i \lor \lnot x_j) is satisfiable
  4. Finding an assignment that satisfies as many clauses of a 2-CNF formula as possible
Show the answer

D. Finding an assignment that satisfies as many clauses of a 2-CNF formula as possible

That is MAX-2-SAT, NP-hard (Garey, Johnson & Stockmeyer, 1976): once some clauses must fail, the clean all-or-nothing structure of implications is lost.

Question 4

Papadimitriou's random walk on a satisfiable 2-CNF formula with nn variables repeatedly picks a false clause and flips one of its two variables at random. Why does it find a model after O(n2)O(n^2) flips in expectation?

  1. Every flip satisfies the chosen clause, so the number of false clauses drops at every step
  2. The number of variables agreeing with a fixed model rises with probability at least 12\tfrac12 per flip, and such a walk on 0,…,n0, \dots, n reaches nn within n2n^2 expected steps
  3. The walk never visits the same assignment twice
  4. It only works on random formulas, where models are plentiful
Show the answer

B. The number of variables agreeing with a fixed model rises with probability at least 12\tfrac12 per flip, and such a walk on 0,…,n0, \dots, n reaches nn within n2n^2 expected steps

Both literals of a false clause are false, but a fixed model makes one of them true, so at least one of the two variables disagrees with the model: a random flip fixes it with probability at least 12\tfrac12. An unbiased walk reflected at 00 needs n2−j2≤n2n^2 - j^2 \le n^2 expected steps to reach nn from jj, and a walk biased upward is no slower.

Further reading

  • B. Aspvall, M. F. Plass & R. E. Tarjan, "A linear-time algorithm for testing the truth of certain quantified boolean formulas," Information Processing Letters 8(3) (1979), 121–123.
  • S. Even, A. Itai & A. Shamir, "On the complexity of timetable and multicommodity flow problems," SIAM Journal on Computing 5(4) (1976), 691–703.
  • C. H. Papadimitriou, "On selecting a satisfying truth assignment," Proceedings of the 32nd IEEE Symposium on Foundations of Computer Science (1991).
  • T. J. Schaefer, "The complexity of satisfiability problems," Proceedings of the 10th ACM Symposium on Theory of Computing (1978).
  • M. Mitzenmacher & E. Upfal, Probability and Computing, 2nd ed. (Cambridge University Press, 2017), chapter 7.