Sub topic 15
Solving 2-SAT with Strongly Connected Components
This chapter applies SCC decomposition to a classic logic problem. It assumes you have read the earlier chapters on the condensation DAG and Kosaraju's algorithm. In particular, it assumes you know that the kosaraju function labels components in a topological order of the condensation. It also assumes you can read basic Boolean logic: AND, OR, NOT, and implication.
The 2-SAT Problem
A 2-SAT instance is a Boolean formula in conjunctive normal form where every clause has at most two literals. A literal is a variable or its negation, such as a or ¬a. A clause is an OR of literals. The formula is the AND of all its clauses. For example:
(a ∨ b) ∧ (¬a ∨ c) ∧ (¬b ∨ ¬c) ∧ (b ∨ c)
The question is whether some assignment of true and false to the variables makes every clause true, and if so, what that assignment is. With three literals per clause (3-SAT), the problem is NP-complete. With two, it can be solved in linear time, and SCCs are the reason.
From Clauses to Implications
The key observation is that a two-literal clause can be rewritten as two implications. The clause (p ∨ q) says "at least one of p, q is true." Equivalently, if p is false then q must be true, and if q is false then p must be true:
(p ∨ q) ≡ (¬p → q) ∧ (¬q → p)
The implication graph has one vertex per literal, which gives 2n vertices for n variables. Each clause adds the two edges above. An edge p → q means "if p is true, q is forced to be true." Following a path chains the forced conclusions together.
| Clause | Edge 1 | Edge 2 |
|---|---|---|
| a ∨ b | ¬a → b | ¬b → a |
| ¬a ∨ c | a → c | ¬c → ¬a |
| ¬b ∨ ¬c | b → ¬c | c → ¬b |
| b ∨ c | ¬b → c | ¬c → b |
Skew symmetry
Every clause contributes a pair of edges that are contrapositives of each other: p → q comes paired with ¬q → ¬p. So the implication graph is skew-symmetric: if you negate every literal and reverse every edge, you get the same graph back. As a result, if a set of literals S forms an SCC, then the negations of S also form an SCC. You can see this in the diagram, where {¬a, b, ¬c} and {a, ¬b, c} are mirror images.
The Satisfiability Test
All literals in one SCC must have the same truth value. Each one implies all the others, so if any of them is true, they are all true.
The formula is unsatisfiable exactly when some variable x has x and ¬x in the same SCC. That situation means x → ¬x and ¬x → x. Setting x true forces it false, and setting it false forces it true. The converse also holds: if no variable shares a component with its own negation, a satisfying assignment exists. The next section builds one.
Building an Assignment from the Condensation
Collapse the implication graph into its condensation DAG and take a topological order. For each variable x, compare the positions of the components containing x and ¬x:
- If x's component comes later in topological order than ¬x's, set x to true.
- Otherwise, set x to false.
The intuition is that later components sit closer to the sinks of the DAG. Choosing the later literal means choosing the one that cannot imply its own negation. If x comes after ¬x, any path between them can only go from ¬x to x. Making x true is then safe.
Why the rule never violates an implication
Write pos(p) for the topological position of p's component. Suppose the rule sets literal p true and literal q false, yet there is an edge p → q. We show this cannot happen.
- p true means pos(¬p) < pos(p).
- The edge p → q means pos(p) ≤ pos(q).
- q false means pos(q) < pos(¬q).
- By skew symmetry the edge ¬q → ¬p also exists, so pos(¬q) ≤ pos(¬p).
Chaining these gives pos(¬p) < pos(p) ≤ pos(q) < pos(¬q) ≤ pos(¬p). That is a strict inequality from pos(¬p) to itself, which is a contradiction. So no edge leads from a true literal to a false one, and every clause is satisfied: a false literal in a clause has an edge to the other literal, which must therefore be true.
Implementation
The code encodes literals as integers. Variable i has positive literal 2*i and negative literal 2*i + 1, so negation is lit ^ 1. It reuses Kosaraju's algorithm from the earlier chapter, which numbers components in topological order. That means "later in topological order" is simply "larger component number."
def kosaraju(n, adj):
visited = [False] * n
order = []
def dfs1(u):
visited[u] = True
for v in adj[u]:
if not visited[v]:
dfs1(v)
order.append(u)
for u in range(n):
if not visited[u]:
dfs1(u)
radj = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]:
radj[v].append(u)
comp = [-1] * n
def dfs2(u, c):
comp[u] = c
for v in radj[u]:
if comp[v] == -1:
dfs2(v, c)
c = 0
for u in reversed(order):
if comp[u] == -1:
dfs2(u, c)
c += 1
return comp
def lit(var, positive=True):
return 2 * var if positive else 2 * var + 1
def two_sat(num_vars, clauses):
n = 2 * num_vars
adj = [[] for _ in range(n)]
for p, q in clauses:
adj[p ^ 1].append(q) # not p -> q
adj[q ^ 1].append(p) # not q -> p
comp = kosaraju(n, adj)
assignment = []
for i in range(num_vars):
t, f = comp[2 * i], comp[2 * i + 1]
if t == f:
return None # x and not x in the same SCC
assignment.append(t > f) # x later in topological order -> true
return assignment
def satisfies(clauses, assignment):
def value(l):
return assignment[l >> 1] != bool(l & 1)
return all(value(p) or value(q) for p, q in clauses)
a, b, c = 0, 1, 2
clauses = [
(lit(a), lit(b)),
(lit(a, False), lit(c)),
(lit(b, False), lit(c, False)),
(lit(b), lit(c)),
]
result = two_sat(3, clauses)
print(result) # [True, False, True]
print(satisfies(clauses, result)) # True
contradiction = [(lit(a), lit(a)), (lit(a, False), lit(a, False))]
print(two_sat(1, contradiction)) # NoneOn the example, Kosaraju assigns component 0 to {¬a, b, ¬c} and component 1 to {a, ¬b, c}. For a and c, the positive literal has the larger number, so both are true. For b, the negative literal has the larger number, so b is false. The assignment a = true, b = false, c = true satisfies all four clauses.
Edge Cases
- Unit clauses. A single-literal clause (x) is written as (x ∨ x). It produces the edge ¬x → x twice, which forces x true whenever ¬x would be chosen. Duplicate edges are harmless.
- Unused variables. A variable that appears in no clause has two isolated literal vertices in separate singleton components. The rule assigns it some value, and any value is fine.
- Multiple solutions. The algorithm returns one valid assignment, not all of them. Counting solutions of 2-SAT is #P-complete, so the SCC method does not extend to counting.
- Large instances. The implication graph has 2n vertices and 2m edges for n variables and m clauses, so the whole solver runs in O(n + m) time. Long implication chains can exceed Python's recursion limit. For real inputs, swap in the iterative SCC implementation from the earlier chapter.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Adding only ¬p → q per clause | Misses forced values, returns invalid assignments | Always add both contrapositive edges |
| Encoding negation as `-lit` or `lit + n` inconsistently | Edges land on wrong vertices | Pick one encoding (such as `lit ^ 1`) and use it everywhere |
| Comparing in the wrong direction | Assignment fails some clauses | Match the comparison to your SCC numbering |
| Using reachability instead of SCC order | Quadratic time | Use one SCC pass and compare component labels |
Exercise
Encode the constraint "exactly one of x and y is true" as 2-SAT clauses, and list the implication edges it creates.
Show answer
"Exactly one" is (x ∨ y) ∧ (¬x ∨ ¬y). The first clause adds ¬x → y and ¬y → x. The second adds x → ¬y and y → ¬x. The graph has two SCCs, {x, ¬y} and {¬x, y}, so the formula is satisfiable and either one can be true.
Exercise
You run Tarjan's algorithm on an implication graph and get the component list [[3, 0], [1, 2]], where literal 0 is x and literal 1 is ¬x. Label each literal by the index of its component in this list. Is x true or false?
Show answer
Tarjan emits components in reverse topological order, so a smaller index means later in topological order. Literal 0 (x) is in component 0, and literal 1 (¬x) is in component 1. Because comp[x] = 0 < comp[¬x] = 1, x comes later topologically, so x is true.
Exercise
Why does the proof that the assignment is valid fail if the implication graph is not skew-symmetric, for example if you add only one edge per clause?
Show answer
Step 4 of the proof uses the contrapositive edge ¬q → ¬p to get pos(¬q) ≤ pos(¬p). Without that edge the chain of inequalities does not close into a contradiction. A true literal could then have an edge to a false literal, and the assignment would break a clause.