Algorithms

Module 10· 9 min read·completed

10. NP-Completeness & Complexity Classes

P, NP, NP-Complete, and NP-Hard classes, polynomial-time reductions, Cook-Levin Theorem, Karp's 21 problems, approximation strategies, and classic polynomial verifiers across C, C++, and Python

NPTEL / GATE CS / UGC NET Advanced Subject Key Exam Questions: Venn diagram relationships (PNPP \subseteq NP, PNPP \ne NP conjecture), Cook-Levin theorem, Polynomial-time reduction direction (ApBA \le_p B), contrapositive deductions, and classic NP-Complete problem equivalences.


1. Prerequisites & What You Should Know#

Before studying complexity theory, ensure you understand:

  • Decision vs Optimization Problems:
    • Optimization: "Find the minimum-weight Hamiltonian cycle in GG."
    • Decision: "Does there exist a Hamiltonian cycle in GG with weight k\le k?"
    • NP-Completeness is strictly formulated for Decision Problems (Yes/No answers). Any optimization problem can be cast as a decision problem via binary search over bound kk.
  • Turing Machines:
    • Deterministic Turing Machine (DTM): Follows exactly one unique execution branch for each state and input symbol.
    • Nondeterministic Turing Machine (NTM): Can evaluate multiple execution branches simultaneously ("magically" guessing the right branch).
  • Polynomial Time (O(nk)O(n^k)): Runtimes like O(n)O(n), O(n2)O(n^2), O(n3)O(n^3) considered "tractable" or "efficient". Runtimes like O(2n)O(2^n) or O(n!)O(n!) considered "intractable".

2. Conceptual Intuition: The Sudoku Analogy & The Millennium Prize#

Diagram / Text
The Sudoku / Jigsaw Puzzle Analogy:
- Finding a Solution from Scratch (SOLVING):
  Solving an expert 25x25 Sudoku or assembling a 2,000-piece white jigsaw puzzle
  requires agonizing trial, error, backtracking, and exponential time (NP Search).

- Checking a Proposed Solution (VERIFYING):
  If someone hands you a completed Sudoku board, checking that every row, column,
  and box contains digits 1-9 takes only a few seconds of simple scanning!
  Verification runs in fast POLYNOMIAL TIME (Class P)!

The PP vs NPNP Question ($1,000,000 Clay Millennium Prize)#

  • PP: Problems that are easy to SOLVE (in polynomial time).
  • NPNP: Problems whose solutions are easy to VERIFY (in polynomial time).
  • Does P=NPP = NP? If someone proves P=NPP = NP, it means any problem that can be verified easily can also be solved easily!
  • Most computer scientists believe PNPP \ne NP.

3. The Four Fundamental Complexity Classes#

Diagram / Text
                  Complexity Universe (Assuming P != NP)
    +-------------------------------------------------------------+
    |                         NP-HARD                             |
    |  (Halting Problem, TSP Optimization, Circuit Minimization)  |
    |                                                             |
    |          +--------------------------------------+           |
    |          |                 NP                   |           |
    |          |    +---------------------------+     |           |
    |          |    |        NP-COMPLETE        |     |           |
    |          |    | (3-SAT, Clique, SubSetSum)|     |           |
    |          |    +---------------------------+     |           |
    |          |                                      |           |
    |          |         +---------------+            |           |
    |          |         |       P       |            |           |
    |          |         | (Sort, Short- |            |           |
    |          |         |  est Path,    |            |           |
    |          |         |  2-SAT, Prim) |            |           |
    |          |         +---------------+            |           |
    |          +--------------------------------------+           |
    +-------------------------------------------------------------+
  1. Class P (Polynomial Time): Decision problems solvable by a Deterministic Turing Machine in O(nk)O(n^k) time.
  2. Class NP (Nondeterministic Polynomial Time): Decision problems verifiable in O(nk)O(n^k) time by a deterministic algorithm when supplied with a polynomial-sized certificate (witness).
  3. NP-Hard: A problem HH is NP-Hard if every problem in NPNP can be polynomial-time reduced to HH: LNP,LpH\forall L \in NP, \quad L \le_p H (Note: HH does NOT need to be in NPNP. For example, the Halting Problem is NP-Hard, but is undecidable!)
  4. NP-Complete (NPC): A problem XX is NP-Complete if:
    1. XNPX \in NP (verifiable in polynomial time), AND
    2. XNP-HardX \in \text{NP-Hard} (at least as hard as everything in NP).

4. Polynomial-Time Reductions (ApBA \le_p B)#

If problem AA reduces to problem BB in polynomial time (ApBA \le_p B), it means: Problem BB is AT LEAST AS HARD AS problem AA.

Diagram / Text
   Input for A ----> [ Poly-Time Transformer: f(x) ] ----> Input for B
                                                                 |
                                                          [ Solver for B ]
                                                                 |
   Answer for A <--------------------------------------- Answer for B

GATE Exam Deductive Rules:#

  • Rule 1 (Easy implies Easy): If ApBA \le_p B and BPB \in P, then APA \in P.
  • Rule 2 (Hard implies Hard): If ApBA \le_p B and AA is NP-Hard, then BB is NP-Hard!
  • GATE TRAP 1: If ApBA \le_p B and APA \in P, this tells us NOTHING about BB (BB could be easy or impossible).
  • GATE TRAP 2: If ApBA \le_p B and BB is NP-Complete, this tells us NOTHING about AA.

5. Cook-Levin Theorem & Karp's 21 NP-Complete Problems#

The Cook-Levin Theorem (1971)#

Stephen Cook and Leonid Levin proved that Boolean Satisfiability (SAT) is NP-Complete from first principles by simulating the transitions of any arbitrary Nondeterministic Turing Machine as a polynomial-sized boolean formula!

Classic Reduction Chain:#

Circuit-SATp3-SATpCliquepVertex CoverpHamiltonian CyclepTSP (Decision)\text{Circuit-SAT} \le_p \text{3-SAT} \le_p \text{Clique} \le_p \text{Vertex Cover} \le_p \text{Hamiltonian Cycle} \le_p \text{TSP (Decision)}

ProblemDescriptionComplexity Status
2-SATBoolean formula with 2 literals per clauseIn P (O(V+E)O(V + E) via SCCs)
3-SATBoolean formula with 3 literals per clauseNP-Complete
Eulerian TourTraverse every edge exactly onceIn P (O(V+E)O(V + E) degree check)
Hamiltonian CycleTraverse every vertex exactly onceNP-Complete
Shortest PathPath with minimum total weightIn P (O((V+E)logV)O((V+E)\log V) Dijkstra)
Longest Simple PathSimple path with maximum weightNP-Complete
Halting ProblemWill a given program terminate?Undecidable (Not in NP!)

6. How Software Engineers Cope with NP-Completeness#

When facing an NP-Complete problem in industry:

  1. Approximation Algorithms: Settle for a provably near-optimal solution in polynomial time (e.g. 2-approximation for Vertex Cover).
  2. Pseudo-Polynomial Algorithms: Use Dynamic Programming if numerical parameters are small (e.g., 0/1 Knapsack runs in O(nW)O(nW) time).
  3. Branch-and-Bound / SAT Solvers: Exploit specialized pruning heuristics that solve most real-world instances in seconds despite worst-case exponential theory.
  4. Special Graph Classes: Many NP-hard problems become solvable in O(n)O(n) time on trees, planar graphs, or chordal graphs.

7. Polynomial-Time Verification in C, C++, and Python#

While solving an NP-Complete problem takes exponential time, verifying a proposed certificate takes only polynomial time.

Subset Sum Certificate Verifier: O(n
#include <stdio.h>
#include <stdbool.h>

/**
 * C Syntax Logic Note:
 * 1. Polynomial Verifier: Takes candidate subset array and target sum.
 * 2. Checks validity in O(candSize * setSize) polynomial time:
 *    every candidate exists in original set AND sum(candidate) == target.
 */

bool verifySubsetSum(const int originalSet[], int setSize, const int candidate[], int candSize, int target) {
    long long sum = 0;

    for (int i = 0; i < candSize; i++) {
        // 1. Verify candidate element exists in original set
        bool exists = false;
        for (int j = 0; j < setSize; j++) {
            if (originalSet[j] == candidate[i]) {
                exists = true;
                break;
            }
        }
        if (!exists) return false;

        sum += candidate[i];
    }

    // 2. Verify sum equals target
    return sum == target;
}

8. GATE & UGC NET Key Exam Insights#

Note

GATE Classic: Undecidable vs NP-Complete

  • The Halting Problem is NOT NP-Complete! It is Undecidable (Unsolvable even with infinite time).
  • NP-Complete problems are strictly Decidable (they can be solved by brute force in exponential time O(2n)O(2^n)).
  • If P=NPP = NP, all NP-Complete problems can be solved in polynomial time, but Undecidable problems remain unsolvable!