Algorithm for 2-Satisfiability problem
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
The 2-SAT problem asks whether a CNF formula with exactly two literals per clause is satisfiable.
Example clause: .
Unlike 3-SAT, 2-SAT is solvable in linear time using strongly connected components (SCCs).
Core Idea: Implication Graph
For each variable x, create two nodes:
x~x
For each clause , add implications:
After building the graph, compute SCCs.
Satisfiability Condition
The formula is satisfiable iff for every variable x, nodes x and ~x are in different SCCs.
If any variable and its negation fall in the same SCC, the formula is unsatisfiable.
Getting an Assignment
After SCC computation (Kosaraju or Tarjan), assign truth values by SCC topological order:
- process SCCs in reverse topological order,
- set a literal true if its SCC appears after its negation SCC.
Python Reference Implementation
Complexity
Let n be variables and m clauses:
- Vertices:
2n - Edges:
2m - Time:
O(n + m) - Space:
O(n + m)
Summary
| Topic | Result |
| Solver model | Implication graph + SCC |
| Unsat check | x and ~x in same SCC |
| Complexity | Linear in graph size |
Related reading
- algorithm for a random space bordered by elements of equal length
- Algorithm for Additive Color Mixing for RGB Values
- Algorithm for autocomplete?
- Algorithm for automatic placement of flowchart shapes
- Algorithm for deleting one element in an single linked list with O1 complexity
- Algorithm for detecting full loop when iterating over a list
- Algorithm for counting common group memberships with big data
- Algorithm for creating a school timetable

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.