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: if and only if .
- 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 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 fails only when both of its literals are false. So if is false then must be true, and if is false then must be true:
The graph is skew-symmetric: the two edges of a clause are contrapositives of each other, so is an edge exactly when is. Reading a path backward and negating every literal gives another path: if and only if . In particular, the strongly connected components come in mirror pairs and .
Which single clause, added to , makes it unsatisfiable?
Show the answer
D.
forces true and then false, while demands true whenever is. In the graph, its edge closes the cycle , which puts and in one component.
The component criterion
Edges are sound implications. A model that satisfies and makes true makes true. So truth flows along every path:
Necessity. If and share a component, then and . A model with true makes true, and a model with false makes true; both are impossible:
Sufficiency. If and always lie in different components, then , so the rule makes exactly one of them true. Suppose a clause ended up with both literals false: and . Its edges and point forward or within a component, so and . Chaining:
Cost. One strongly connected components computation on vertices and edges, then one scan over the variables:
Tarjan's algorithm numbers components in reverse topological order, so the rule becomes " is true if and only if "; with Kosaraju's numbering, sources first, the comparison flips.
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 , with numbered to , the call two_sat(4, [(1, 2), (-1, 3), (-2, 3), (-3, -4)], tarjan) returns , . 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 and both false before looking at breaks that clause. Choices work if each is propagated before the next is made: set , 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:
| Constraint | Clauses |
|---|---|
| must hold | |
| if then | |
| or | |
| not both and | |
| and | |
| (exactly one) | and |
| at most one of | clauses , or clauses with prefix variables |
"At most one" in linear size. Introduce , meaning "some of is true", with the clauses , and . If and with were both true, the chain would fail. With at most one true variable, setting each to its intended meaning satisfies every clause. That is clauses instead of .
| Problem (in our words) | The binary choice | The 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 wish | invite each person or not | one clause per guest |
| Each map label sits above or below its point, and two overlapping label positions cannot both be used | the position of each label | for every overlapping pair |
| Each of flags goes at one of two given spots; maximize the smallest distance between two flags | the spot of each flag | binary search on the distance : every pair of spots closer than gives a "not both" clause, and each test is a 2-SAT instance with clauses |
| Workshops run in the morning or the afternoon; some pairs share a speaker and need different slots, some must run together, some are fixed | the slot of each workshop | , and one-literal clauses |
Which of these problems reduces to 2-SAT?
- Color every country on a map red, green or blue so that neighbors differ
- 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 runs in the afternoon then so does workshop
- Choose the fewest servers so that every client is next to a chosen server
- Satisfy as many as possible of a list of constraints of the form " or "
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 runs in the afternoon then so does workshop
One Boolean variable per workshop (true for morning). "Different slots" is , "same slot" is , and "if is in the afternoon then so is " is , the clause . 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:
| Problem | Complexity |
|---|---|
| 2-SAT | ; NL-complete: its complement is NL-complete (Jones, Lien & Laaser, 1976), and NL is closed under complement (Immerman; Szelepcsényi) |
| Quantified 2-CNF formulas | (Aspvall, Plass & Tarjan, 1979) |
| 3-SAT | NP-complete (Cook, 1971) |
| MAX-2-SAT | NP-hard (Garey, Johnson & Stockmeyer, 1976); approximable within a factor of about (Lewin, Livnat & Zwick), which is optimal if the Unique Games Conjecture holds (Austrin; Brakensiek, Huang & Zwick) |
| 2-SAT: counting the models | -complete, even for formulas without negations (Valiant, 1979) |
Fix a model and let count the variables on which the current assignment agrees with . A false clause has both literals false, but makes one of them true, so at least one of its two variables disagrees with . A random flip of one of the two therefore raises with probability at least :
For the unbiased walk on , reflected at , let be the expected number of steps to reach from . Then , and , solved by
A walk pushed upward at least as often reaches no later in expectation, and it may stop earlier at another model. By Markov's inequality, flips succeed with probability at least , 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 -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 is the pair of implications and ; the implication graph on literals is skew-symmetric: if and only if .
- A 2-CNF formula is satisfiable if and only if no shares a component with ; then making true when its component comes after 's in topological order satisfies it, all in (Aspvall, Plass & Tarjan, 1979).
- 2-SAT models binary choices with pairwise constraints: implications, equalities, exclusions, "at most one" with 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.
In the implication graph of a 2-CNF formula there is a path from literal to literal . Which other path must exist?
- From to
- From to
- From to
- From to
Show the answer
C. From to
Each clause contributes an edge and its contrapositive, so reversing a path and negating its literals gives a path: implies . This is the contrapositive of " implies ".
Tarjan's algorithm on an implication graph gives and . What value does the standard rule give ?
- True: Tarjan numbers components sinks first, so 's component comes later in topological order
- False: 's component has the smaller number
- Either value: since the components differ, is unconstrained
- Nothing yet: the formula may still be unsatisfiable
Show the answer
A. True: Tarjan numbers components sinks first, so 's component comes later in topological order
Smaller Tarjan numbers come later in topological order, so and the rule makes true. Intuitively, a literal late in the order implies little, so making it true is safe.
Which of these problems is NP-hard?
- Deciding whether a 2-CNF formula is satisfiable
- Deciding a quantified 2-CNF formula such as
- Deciding whether a 2-CNF formula whose clauses all have the form is satisfiable
- 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.
Papadimitriou's random walk on a satisfiable 2-CNF formula with variables repeatedly picks a false clause and flips one of its two variables at random. Why does it find a model after flips in expectation?
- Every flip satisfies the chosen clause, so the number of false clauses drops at every step
- The number of variables agreeing with a fixed model rises with probability at least per flip, and such a walk on reaches within expected steps
- The walk never visits the same assignment twice
- 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 per flip, and such a walk on reaches within 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 . An unbiased walk reflected at needs expected steps to reach from , 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.