1.5Common Running Times: Polynomial, Exponential and Factorial
Covers IGNOU MCS-211 §1.4
Some problems seem to require trying every subset or every ordering of the input. This page shows how such searches lead to , and running times, and why the last two become impossible even for modest .
Polynomial time,
An algorithm runs in polynomial time if for some fixed constant . Linear, quadratic and cubic time are all polynomial.
The study material’s example is the independent set problem.
Brute force for a fixed :
for each subset s of k vertices do
if no two vertices of s are joined by an edge then
print "s is an independent set"
stop
end if
end for
print "no independent set of size k"- The number of -vertex subsets is .
- Checking one subset means testing each of its pairs, which is .
- Total: . Because is a constant, is a constant too, so the time is — polynomial, but with a large exponent if is large.
Exponential time,
Now drop the fixed and ask for the largest independent set. We must consider subsets of every size, which means all subsets of the vertices.
best ← empty set
for each subset s of the n vertices do // 2^n subsets
if s is independent and |s| > |best| then // O(n^2) pair checks
best ← s
end if
end for
return bestEach subset has at most vertices, so checking it takes at most pair tests. The total is .
from itertools import combinations
# A small graph: 5 nodes, edges listed as pairs.
nodes = [1, 2, 3, 4, 5]
edges = {(1, 2), (1, 3), (2, 4), (3, 4), (4, 5)}
def adjacent(u, v):
return (u, v) in edges or (v, u) in edges
def is_independent(subset):
# check every pair of nodes in the subset: O(k^2) pairs
return all(not adjacent(u, v) for u, v in combinations(subset, 2))
# Part 1: is there an independent set of size k? (about n^k subsets)
k = 3
tried = 0
for s in combinations(nodes, k):
tried += 1
if is_independent(s):
print(f"size {k}: found {s} after trying {tried} subsets")
break
else:
print(f"size {k}: none found after trying {tried} subsets")
# Part 2: largest independent set (all 2^n subsets)
best = ()
tried = 0
for size in range(len(nodes) + 1):
for s in combinations(nodes, size):
tried += 1
if is_independent(s) and len(s) > len(best):
best = s
print(f"largest: {best} after trying {tried} subsets (2^5 = {2**5})")size 3: found (2, 3, 5) after trying 8 subsets
largest: (2, 3, 5) after trying 32 subsets (2^5 = 32)Notice that the size-3 search had to skip seven non-independent subsets before it found ; stopping at the first failure would have reported nothing.
Factorial time,
grows even faster than . It appears when brute force tries every ordering (permutation) or every one-to-one matching.
- Matching by brute force. To pair boys with girls in every possible way, the first boy has choices, the second , and so on: possible perfect matchings.
- Travelling salesman problem (TSP). Given cities and the distance between every pair, find the shortest tour that visits every city exactly once and returns to the start. Fix the starting city (every tour passes through it anyway); the remaining cities can be visited in orders. With symmetric distances each tour is counted twice (forwards and backwards), so there are different tours. In big-O terms this is still factorial time.
from itertools import permutations
# Distances between 4 cities A, B, C, D (symmetric).
dist = {
("A", "B"): 10, ("A", "C"): 15, ("A", "D"): 20,
("B", "C"): 35, ("B", "D"): 25, ("C", "D"): 30,
}
def d(x, y):
return dist[(x, y)] if (x, y) in dist else dist[(y, x)]
start = "A"
others = ["B", "C", "D"]
best_tour, best_len, count = None, None, 0
for order in permutations(others): # (n-1)! orders with A fixed
tour = (start,) + order + (start,)
length = sum(d(tour[i], tour[i + 1]) for i in range(len(tour) - 1))
count += 1
print(" -> ".join(tour), "=", length)
if best_len is None or length < best_len:
best_tour, best_len = tour, length
print("tours tried:", count)
print("shortest:", " -> ".join(best_tour), "=", best_len)A -> B -> C -> D -> A = 95
A -> B -> D -> C -> A = 80
A -> C -> B -> D -> A = 95
A -> C -> D -> B -> A = 80
A -> D -> B -> C -> A = 95
A -> D -> C -> B -> A = 95
tours tried: 6
shortest: A -> B -> D -> C -> A = 80With 4 cities there are orders, and each tour appears twice (e.g. A→B→D→C→A and A→C→D→B→A both have length 80), giving different tours.
How fast do these grow?
import math
# How many basic steps each running time needs for a few input sizes.
sizes = [1, 2, 4, 8, 16, 32]
print(f"{'n':>3} {'log2 n':>7} {'n log2 n':>9} {'n^2':>6} {'n^3':>7} {'2^n':>11} {'n!':>10}")
for n in sizes:
fact = math.factorial(n)
fact_text = f"{fact}" if fact < 10**9 else f"{fact:.1e}"
two_n = 2 ** n
print(f"{n:>3} {math.log2(n):>7.0f} {n * math.log2(n):>9.0f} {n**2:>6} "
f"{n**3:>7} {two_n:>11} {fact_text:>10}") n log2 n n log2 n n^2 n^3 2^n n!
1 0 0 1 1 2 1
2 1 2 4 8 4 2
4 2 8 16 64 16 24
8 3 24 64 512 256 40320
16 4 64 256 4096 65536 2.1e+13
32 5 160 1024 32768 4294967296 2.6e+35At a billion steps per second, steps take about 4 seconds, but steps would take about years.
Green and highlighted classes are considered feasible (polynomial); red classes are infeasible for large n.
Key takeaways
- for constant is polynomial time; trying all -subsets gives it.
- Trying all subsets gives about cases; the maximum independent set brute force is .
- Trying all orderings or matchings gives about cases (TSP brute force: tours).
- Running time belongs to an algorithm: bipartite matching has a polynomial algorithm even though its brute force is .
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
In the graph with vertices 1–5 and edges 1–2, 1–3, 2–4, 3–4, 4–5, show that {2, 3, 5} is independent and that {1, 4, 5} is not.
Show worked answer
{2, 3, 5}: the pairs are 2–3, 2–5, 3–5, and none of them is an edge, so the set is independent. {1, 4, 5}: the pair 4–5 is an edge, so the set is not independent (1–4 and 1–5 are not edges, but one edge is enough to fail).