MCS-211 · Block 1 Unit 1

Basics of an Algorithm and its Properties

Section 5 of 9

Block 1 · Unit 1Basics of an Algorithm and its Properties10 min · Section 5 of 9

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 O(nk)O(n^k), O(2n)O(2^n) and O(n!)O(n!) running times, and why the last two become impossible even for modest nn.

Polynomial time, O(nk)O(n^k)

An algorithm runs in polynomial time if T(n)=O(nk)T(n) = O(n^k) for some fixed constant kk. Linear, quadratic and cubic time are all polynomial.

The study material’s example is the independent set problem.

Brute force for a fixed kk:

Independent set of size k pseudocode
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 kk-vertex subsets is (nk)=n(n−1)⋯(n−k+1)k!≤nk\binom{n}{k} = \dfrac{n(n-1)\cdots(n-k+1)}{k!} \le n^k.
  • Checking one subset means testing each of its (k2)=k(k−1)2\binom{k}{2} = \dfrac{k(k-1)}{2} pairs, which is O(k2)O(k^2).
  • Total: O(k2nk)O(k^2 n^k). Because kk is a constant, k2k^2 is a constant too, so the time is O(nk)O(n^k) — polynomial, but with a large exponent if kk is large.

Exponential time, O(2n)O(2^n)

Now drop the fixed kk and ask for the largest independent set. We must consider subsets of every size, which means all 2n2^n subsets of the nn vertices.

Maximum independent set pseudocode
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 best

Each subset has at most nn vertices, so checking it takes at most (n2)=O(n2)\binom{n}{2} = O(n^2) pair tests. The total is O(n2⋅2n)O(n^2 \cdot 2^n).

Python · independent_set.py
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})")
Output
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 {2,3,5}\{2, 3, 5\}; stopping at the first failure would have reported nothing.

Factorial time, O(n!)O(n!)

n!=n×(n−1)×⋯×2×1n! = n \times (n-1) \times \dots \times 2 \times 1 grows even faster than 2n2^n. It appears when brute force tries every ordering (permutation) or every one-to-one matching.

  • Matching by brute force. To pair nn boys with nn girls in every possible way, the first boy has nn choices, the second n−1n - 1, and so on: n!n! possible perfect matchings.
  • Travelling salesman problem (TSP). Given nn 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 n−1n - 1 cities can be visited in (n−1)!(n-1)! orders. With symmetric distances each tour is counted twice (forwards and backwards), so there are (n−1)!/2(n-1)!/2 different tours. In big-O terms this is still factorial time.
Python · tsp_brute.py
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)
Output
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 = 80

With 4 cities there are (4−1)!=6(4-1)! = 6 orders, and each tour appears twice (e.g. A→B→D→C→A and A→C→D→B→A both have length 80), giving 6/2=36/2 = 3 different tours.

How fast do these grow?

Python · growth_table.py
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}")
Output
  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+35

At a billion steps per second, 2322^{32} steps take about 4 seconds, but 32!32! steps would take about 8×10188 \times 10^{18} years.

1constant
→
log nlogarithmic
→
nlinear
→
n log nlinearithmic
→
n², n³, nᵏpolynomial
→
2ⁿexponential
→
n!factorial

Green and highlighted classes are considered feasible (polynomial); red classes are infeasible for large n.

Growth ladder (slowest to fastest)

Key takeaways

  • O(nk)O(n^k) for constant kk is polynomial time; trying all kk-subsets gives it.
  • Trying all subsets gives about 2n2^n cases; the maximum independent set brute force is O(n22n)O(n^2 2^n).
  • Trying all orderings or matchings gives about n!n! cases (TSP brute force: (n−1)!/2(n-1)!/2 tours).
  • Running time belongs to an algorithm: bipartite matching has a polynomial algorithm even though its brute force is n!n!.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

How many subsets of size 2 does a set of 5 vertices have?

Show answer

Answer: B. 10

C(5, 2) = 5 × 4 / 2 = 10. The value 32 is 2⁵, the number of all subsets.

Question 2 · multiple choice

Which statement is correct?

Show answer

Answer: C. n3=O(2n)n^3 = O(2^n)

Every polynomial grows more slowly than 2ⁿ, so n³ = O(2ⁿ). n²2ⁿ is not O(2ⁿ) because the extra n² is not a constant.

Question 3 · multiple choice

With the start city fixed and symmetric distances, how many different tours does brute force TSP check for 5 cities?

Show answer

Answer: C. 12

(5 − 1)! = 24 orders, and each tour is counted twice (forwards and backwards), so 24 / 2 = 12. 120 = 5! counts each tour 10 times.

Question 4 · multiple choice

Finding an independent set of a fixed size kk by brute force takes:

Show answer

Answer: A. O(nk)O(n^k)

There are at most nᵏ subsets of size k and each check is O(k²), a constant. 2ⁿ would be the cost of trying all subsets.

Question 5 · multiple choice

Which problem has a polynomial-time algorithm, even though brute force takes n!n! time?

Show answer

Answer: B. Bipartite matching

Bipartite matching is solved in polynomial time with augmenting paths. No polynomial algorithm is known for the other three.

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).

↑ ↓ move↵ openTab switch type