Lesson 2 +30 XP

Algorithm Analysis, Loop Complexity & Asymptotic Notations

Algorithm Analysis, Loop Complexity & Asymptotic Notations

Algorithm Analysis predicts the resources an algorithm requires as a function of input size n, independent of hardware or compiler differences (A Priori theoretical analysis vs A Posteriori empirical timing).

1. Characteristics & Categories of an Algorithm

An Algorithm is a finite, step-by-step set of instructions to solve a problem. Every valid algorithm must satisfy 5 key characteristics:

  1. Input: Zero or more externally supplied quantities.
  2. Output: At least one quantity produced as a result.
  3. Definiteness: Every instruction is clear and unambiguous.
  4. Finiteness: Terminates after a finite number of steps for all valid inputs.
  5. Effectiveness: Every step is basic enough to be carried out in finite time (e.g., with pencil and paper).

2. Space Complexity

Total space S(P) = c + SP(n) consists of:

  1. Instruction Space: Compiled machine code (fixed).
  2. Data Space: Constants, simple variables, and arrays/structs.
  3. Environment Stack Space: Return addresses, parameters, and local variables pushed during function calls and recursion.

2. Time Complexity & Loop Pattern Analysis

We count primitive operations (assignments, comparisons, arithmetic) rather than wall-clock seconds:

Loop StructureIterationsTime Complexity
for (i = 0; i < n; i++)nO(n) (Linear)
for (i = 0; i < n; i += 2)n / 2O(n) (Linear)
for (i = 1; i <= n; i *= 2)2k ≤ n ⇒ k = ⌊log2 n⌋O(log n) (Logarithmic)
Nested independent loops (0..n, 0..n)n × nO(n2) (Quadratic)
Outer linear (n) + inner logarithmic (log n)n log nO(n log n) (Linearithmic)
Dependent triangular loop (j = 0; j < i; j++)(n(n-1) / 2)O(n2) (Quadratic)

3. Best, Average & Worst Case

  • Best Case (Ω intuition): Minimum steps for a given n (e.g., target at index 0 in Linear Search: O(1)).
  • Worst Case (O intuition): Maximum steps over all inputs of size n - gives a strict performance guarantee.
  • Average Case: Expected number of steps assuming a probability distribution over all valid inputs.

4. Asymptotic Notations

  1. Big-O (O - Asymptotic Upper Bound): f(n) = O(g(n)) iff ∃ c > 0, n0 ≥ 0 such that 0 ≤ f(n) ≤ c · g(n) for all n ≥ n0.
  2. Big-Omega (Ω - Asymptotic Lower Bound): f(n) = Ω(g(n)) iff ∃ c > 0, n0 ≥ 0 such that f(n) ≥ c · g(n) for all n ≥ n0.
  3. Theta (Θ - Asymptotic Tight Bound): f(n) = Θ(g(n)) iff ∃ c1, c2 > 0, n0 ≥ 0 such that c1 g(n) ≤ f(n) ≤ c2 g(n) for all n ≥ n0.
  4. Little-o (o) & Little-omega (ω): Strict (non-tight) bounds where the ratio f(n)/g(n) → 0 as n → ∞ (for o), or f(n)/g(n) → ∞ (for ω).

Worked Proofs (Coefficient Sum Method)

  • Show 4n + 6 = O(n): For n ≥ 1, 4n + 6 ≤ 4n + 6n = 10n. Choose c = 10, n0 = 1.
  • Show 4x2 - 5x + 3 = O(x2): For x ≥ 1, |4x2 - 5x + 3| ≤ 4x2 + 5x2 + 3x2 = 12x2. Choose c = 12, n0 = 1.
  • Note: n2 + n = O(n3) is also valid because Big-O is an upper bound (even if not tight).

Growth Rate Hierarchy

1 < log n < √(n) < n < n log n < n2 < n3 < 2n < n!

5. Algorithm Design Paradigms

  • Brute Force: Exhaustively checks candidates; simple but often slow.
  • Divide & Conquer: Splits problem into independent subproblems, solves recursively, and merges (Merge Sort, Quick Sort, Binary Search).
  • Greedy: Picks the locally optimal choice at each step without backtracking (Kruskal, Prim, Dijkstra). Counterexample: For coins {1, 7, 10} making 15, Greedy picks 10 + 1 + 1 + 1 + 1 + 1 (6 coins), whereas optimal is 7 + 7 + 1 (3 coins).
  • Dynamic Programming: Solves overlapping subproblems once and stores results (Floyd-Warshall, Knapsack).
  • Backtracking & Branch and Bound: Explores state-space trees and prunes invalid or suboptimal branches (N-Queens).

Characteristics of an Algorithm (from the notes)

An algorithm is a finite, step-by-step procedure to solve a problem. Every algorithm must be:

CharacteristicMeaning
UnambiguousEach step and its inputs/outputs have exactly one meaning
InputZero or more well-defined inputs
OutputAt least one well-defined output
FinitenessTerminates after a finite number of steps
FeasibilityCan be carried out with available resources
IndependentWritten as steps that do not depend on any programming language

Categories of algorithms by task: Search (find an item), Sort (arrange in order), Insert (add an item), Update (change an existing item), Delete (remove an item).

Pseudocode and Primitive Operations

Pseudocode is a high-level, language-independent description of an algorithm-more structured than English, less detailed than a program. For analysis we count primitive operations, each assumed to take constant time:

  • assigning a value to a variable,
  • calling a method / returning from it,
  • performing an arithmetic operation,
  • comparing two numbers,
  • indexing into an array, following a pointer.

Types of Algorithms (Design Strategies)

TypeIdeaExample
Simple recursiveSolve the base case directly, recur on a simpler subproblemFactorial, counting list elements
BacktrackingDepth-first search of choices; undo a choice that fails8-Queens, maze solving
Divide and conquerSplit into independent subproblems, solve, combineMerge sort, quick sort, binary search
Dynamic programmingRemember answers of overlapping subproblemsFibonacci with a table, 0/1 knapsack
GreedyTake the best-looking choice at each stepKruskal, Prim, Dijkstra, coin change
Branch and boundExplore a tree of choices, prune branches whose bound is worse than the best found0/1 knapsack, travelling salesman
Brute forceTry every possibilityNaive string matching, linear search
RandomizedUse a random number to make a decisionRandomized quick sort (random pivot)

Rules for Asymptotic Notation

  1. Drop constant factors: if f(n) = c · g(n) then f(n) = O(g(n)).
  2. Drop lower-order terms: in a polynomial of degree d, f(n) = O(nd).
  3. Sum rule: if T1 = O(f) and T2 = O(g), then T1 + T2 = O(max(f, g)).
  4. Product rule: T1 · T2 = O(f · g) (nested loops multiply).
  5. Use the smallest possible class: say 2n is O(n), not O(n2); say 3n + 5 is O(n), not O(3n).

Worked Big-O Proofs (notes' examples)

f(n)Big-OWitnesses (c, n₀)
7n - 3O(n)7n - 3 ≤ 7n for n ≥ 1, so c = 7, n₀ = 1
50 n log nO(n log n)c = 50, n₀ = 1
8n2 log n + 5n2 + nO(n2 log n)≤ 8n2log n + 5n2log n + n2log n = 14 n2 log n for n ≥ 2; c = 14, n₀ = 2
5n2 + 3n + 20O(n2)≤ 5n2 + 3n2 + 20n2 = 28n2 for n ≥ 1; c = 28, n₀ = 1
n(n+1)/2O(n2)= n2/2 + n/2 ≤ n2 for n ≥ 1; c = 1, n₀ = 1

Dependent (Triangular) Loops

C
for (i = 1; i <= n; i++)
    for (j = 1; j <= i; j++)
        sum++;              /* runs 1 + 2 + ... + n times */

The inner loop runs i times, so the total is 1 + 2 + … + n = (n(n+1) / 2) = O(n2). A loop whose control variable is multiplied (i = i * 2) runs log2 n times, so a linear loop around it gives O(n log n).

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Define Asymptotic Notations (O, Ω, Θ). Prove that 4n + 6 = O(n) and 4x2 - 5x + 3 = O(x2). (7.5 Marks)
  • Write: Formal inequality definitions with constants c, n0, graph/growth hierarchy (1 &lt; log n &lt; n &lt; n log n &lt; n2 &lt; 2n &lt; n!), and step-by-step coefficient-sum proofs.
  • Q2. Differentiate between Divide &amp; Conquer, Greedy, and Dynamic Programming with one example each. (5 Marks)
  • Write: Subproblem independence (D&amp;C: Merge Sort), local optimal choice without backtracking (Greedy: Kruskal's + coin-change counterexample), overlapping subproblems + memoization (DP: Floyd-Warshall).