Introduction to Algorithm Analysis Study Notes

Introduction to Algorithms

  • Definition: An algorithm is a step-by-step procedure for solving a specific computational problem.

  • Composition: It consists of a finite set of instructions that, when followed, accomplish a particular task.

  • Multiple Solutions: For any given problem, there can be infinitely many correct algorithms.

  • Optimization Goals: A high-quality algorithm should be optimized for both time and space efficiency.

Characteristics and Properties of an Algorithm

  • Input: An algorithm must have zero or more quantities supplied externally.

  • Output: At least one output must be produced.

  • Definiteness: Every instruction must be clear and unambiguous. Operations that are not permitted include:

    • −1\sqrt{-1}

    • 150\frac{15}{0}

    • Ambiguous commands like "add 6 or 7 to x"

  • Finiteness: The algorithm must terminate after a finite number of steps.

    • Note: Continuous programs like Operating Systems (which stay in a "wait" loop), database servers, or web servers are providing services and are not classified as algorithms because they do not necessarily terminate.

  • Effectiveness: Every instruction must be basic enough that it can be carried out by a person using only pencil and paper in a finite amount of time.

  • Computational Procedures: Algorithms that satisfy both definiteness and effectiveness are also known as computational procedures.

Algorithm vs. Program

Feature

Algorithm

Program

Phase

Used during the design phase of the software development life cycle.

Used during the implementation/development phase.

Knowledge

Requires problem or domain knowledge (e.g., Doctors for hospitals, Accountants for accounts).

Requires a programmer with language expertise.

Language

Uses natural language, mathematical notation, or pseudo-code.

Written in specific programming languages like C, C++, Java, or Python.

Dependency

Independent of hardware, software, or operating systems.

Dependent on hardware, software, and operating systems.

Process

Involves analysis of the design.

Involves testing and debugging.

Finiteness

Must satisfy the finiteness condition (must terminate).

Does not have to satisfy the finiteness condition.

Algorithm Specification Methods

  • Natural Language: Typically written in common languages like English.

  • Graphical Representation: Using flowcharts. This method is effective primarily for small and simple algorithms.

  • Pseudo-code: Describes algorithms as programs using a syntax that resembles programming languages like C or Pascal.

Analysis of Algorithms: Time and Space Complexity

  • Analysis Objective: Determining how much time and memory space an algorithm requires to solve a problem.

  • Performance Metrics:

    • Time Complexity: The total computer time an algorithm needs to run to completion.

    • Space Complexity: The total memory an algorithm needs to run to completion.

  • External Factors: Algorithm performance is influenced by the hardware, operating system, compiler, size of input (n)(n), and nature of the input.

Detailed Time Complexity Components

  • Program Time: Total time is the sum of compile time and run/execution time.

  • Independence of Compile Time: Compile time is generally independent of the specific instance characteristics of the problem.

  • Affecting Factors:

    1. Characteristics of the compiler used.

    2. Physical clock and machine on which the program executes.

    3. Multiuser environment overhead.

    4. Number of program steps.

  • Time Formula: For any algorithm AA, the time is calculated as:

    • Time(A)=FixedTime(A)+InstanceTime(A)Time(A) = Fixed Time(A) + Instance Time(A)

  • Measurement of Complexity: Time complexity quantifies the amount of time taken as a function of the input length nn. It measures the variation in execution time relative to the number of operations performed, rather than the absolute time.

Step Count Definitions for Code Statements

  • Comments: Zero (0) steps.

  • Assignment Statements: One (1) step (if no external algorithm calls are involved).

  • Iterative Statements: Step count is assigned to the control part of the statement.

  • Total Calculation: If a statement inside a loop repeats, the frequency is multiplied by the time required for a single execution.

Common Problems and Primitive Operations

Problem

Associated Primitive Operation

Input Size

Search for xx in array AA

Comparison of xx with elements of AA

Array size

Multiply 2 matrices

Multiplication and Addition

Dimension of the matrix

Sorting

Comparison

Array size

Graph Traversal

Edge traversal frequency

Number of vertices and edges

Recursive Procedure

Number of recursive calls

Array size/Input size

Factorial

Multiplication

The input number

LCM(a, b)

Basic arithmetic (division, subtraction)

Bits needed to represent a and b

Space Complexity Components

  • Fixed Component: Independent of input/output characteristics. Includes:

    • Instruction space (code).

    • Space for simple variables and fixed-size component variables.

    • Space for constants.

  • Variable Component: Dependent on the problem instance. Includes:

    • Referenced variables.

    • Recursion stack space.

    • Structural components (Linked lists, heaps, trees, graphs).

  • Space Formula:

    • S(A)=c+SA(Instance Characteristics)S(A) = c + S_A(\text{Instance Characteristics})

    • cc is the constant fixed component.

Frequency Count Method: Case Studies

Swapping Two Numbers
  • Code: temp = a; (1), a = b; (1), b = temp; (1).

  • Time Function: f(n)=3f(n) = 3 (Constant, O(1)O(1)).

  • Space Function: S(n)=3 wordsS(n) = 3 \text{ words} (Constant, O(1)O(1)).

Sum of Array Elements
  • Algorithm: Sum(A, n) initializes s = 0, then loops for (i=0; i < n; i++) to add s = s + A[i] and return s.

  • Time Analysis:

    • s = 0: 1 time

    • for(i=0; i<n; i++): i=0 (1 time), i < n (n+1n+1 times), i++ (nn times). Summed control count is 2n+22n + 2.

    • s = s + A[i]: nn times.

    • return s: 1 time.

    • Total Time Function: f(n)=2n+3f(n) = 2n + 3 (Degree O(n)O(n)).

  • Space Analysis:

    • Variables: AA (nn words), nn (1), ss (1), ii (1).

    • Total Space Function: S(n)=n+3S(n) = n + 3 (Degree O(n)O(n)).

Matrix Addition (n×nn \times n matrix)
  • Time Analysis: Nested loops. Outer loop runs n+1n+1 times. Inner loop runs n(n+1)n(n+1) times. Calculation statement runs n2n^2 times.

  • Total Time Function: f(n)=2n2+2n+1f(n) = 2n^2 + 2n + 1 (Degree O(n2)O(n^2)).

  • Space Analysis: Arrays A,B,CA, B, C each take n2n^2 space. Scalars n,i,jn, i, j take 1 each.

  • Total Space Function: S(n)=3n2+3S(n) = 3n^2 + 3 (Degree O(n2)O(n^2)).

Matrix Multiplication (n×nn \times n matrix)
  • Loop Structure: Triple nested loops (indices i,j,ki, j, k).

  • Time Analysis:

    • Outer loop (ii): n+1n+1

    • Middle loop (jj): n(n+1)n(n+1)

    • Assignment C[i,j] = 0: n2n^2

    • Inner loop (kk): n2(n+1)n^2(n+1)

    • Calculation: n3n^3

  • Total Time Function: f(n)=2n3+3n2+2n+1f(n) = 2n^3 + 3n^2 + 2n + 1 (Degree O(n3)O(n^3)).

  • Space Complexity: S(n)=3n2+4S(n) = 3n^2 + 4 (Degree O(n2)O(n^2)).

Complexity Analysis of Typical Code Patterns

Pattern

Time Analysis

Big-O

for (i=0; i<n; i++)

2n+12n+1

O(n)O(n)

for (i=n; i>0; i--)

2n+12n+1

O(n)O(n)

for (i=1; i<n; i=i+2)

n+12\frac{n+1}{2}

O(n)O(n)

for (i=0; i*i < n; i++)

n\sqrt{n}

O(n)O(\sqrt{n})

for (i=1; k<=n; i++) { k=k+i; }

k=p(p+1)2>n  ⟹  p>nk = \frac{p(p+1)}{2} > n \implies p > \sqrt{n}

O(n)O(\sqrt{n})

for (i=1; i<n; i=i*2)

2k=n  ⟹  k=log⁡2(n)2^k = n \implies k = \log_2(n)

O(log⁡2n)O(\log_2 n)

for (i=n; i>=1; i=i/2)

n2k=1  ⟹  k=log⁡2(n)\frac{n}{2^k} = 1 \implies k = \log_2(n)

O(log⁡2n)O(\log_2 n)

Double nested loops (standard)

n×nn \times n

O(n2)O(n^2)

for (i=0; i<n; i++) then for (j=0; j<m; j++)

n+mn + m

O(n+m)O(n+m)

for (i=0; i<n; i++) { for (j=0; j<log n; ...)}

nlog⁡nn \log n

O(nlog⁡n)O(n \log n)

Multi-loop: sum=0; for i to n { for j to i*i { for k to j { sum++ }}}

n×n2×n2n \times n^2 \times n^2

O(n5)O(n^5)

Growth Rate Comparison and Ordering

Functions ordered by growth rate (from slowest to fastest):

  1. 2/N2/N

  2. 3737 (Constant)

  3. N\sqrt{N}

  4. NN

  5. Nlog⁡log⁡NN \log \log N

  6. Nlog⁡NN \log N (equivalent to Nlog⁡(N2)N \log(N^2), as the constant factor 2 is dropped)

  7. Nlog⁡2NN \log^2 N

  8. N1.5N^{1.5}

  9. N2N^2

  10. N2log⁡NN^2 \log N

  11. N3N^3

  12. 2N/22^{N/2}

  13. 2N2^N

Common Complexity Classes

  • O(1)O(1) (Constant): Finding if a number is even/odd, checking if an item is null, printing the first element of a list.

  • O(log⁡bn)O(\log_b n) (Logarithmic): Binary Search.

  • O(n)O(n) (Linear): Finding max/min values in an array, linear search.

  • O(nlog⁡bn)O(n \log_b n) (Linearithmic): Merge sort, Quick sort.

  • O(n2)O(n^2) (Quadratic): Bubble sort, Selection sort, finding duplicate values in a collection.

  • O(nk)O(n^k) (Polynomial): Matrix multiplication (O(n3)O(n^3)).

  • O(cn)O(c^n) (Exponential): Power set (O(2n)O(2^n)), Fibonacci, Travelling Salesman via dynamic programming.`

  • O(n!)O(n!) (Factorial): String permutations, Brute-force Travelling Salesman.

Asymptotic Notations

Asymptotic analysis focuses on the "significant term" of the function, describing limiting behavior as nn tends to infinity.

Big-Oh (O)(O): Asymptotic Upper Bound
  • Definition: f(n)=O(g(n))f(n) = O(g(n)) if there exist positive constants cc and n0n_0 such that 0≤f(n)≤c⋅g(n)0 \le f(n) \le c \cdot g(n) for all n≥n0n \ge n_0.

  • Usage: Represents a tight or loose upper bound. It is preferred to provide the closest possible function.

  • Example: 2n+3≤5n2n + 3 \le 5n for n≥1n \ge 1, so 2n+3=O(n)2n + 3 = O(n).

Big-Omega (Ω)(\Omega): Asymptotic Lower Bound
  • Definition: f(n)=Ω(g(n))f(n) = \Omega(g(n)) if there exist positive constants cc and n0n_0 such that f(n)≥c⋅g(n)f(n) \ge c \cdot g(n) for all n≥n0n \ge n_0.

  • Usage: Represents the guaranteed minimum performance.

  • Example: 2n+3≥1⋅n2n + 3 \ge 1 \cdot n for n≥1n \ge 1, so 2n+3=Ω(n)2n + 3 = \Omega(n).

Theta (Θ)(\Theta): Asymptotic Tight Bound
  • Definition: f(n)=Θ(g(n))f(n) = \Theta(g(n)) if there exist positive constants c1,c2,c_1, c_2, and n0n_0 such that c1⋅g(n)≤f(n)≤c2⋅g(n)c_1 \cdot g(n) \le f(n) \le c_2 \cdot g(n) for all n≥n0n \ge n_0.

  • Usage: Used for the average bound. An algorithm is Θ(g(n))\Theta(g(n)) only if it is both O(g(n))O(g(n)) and Ω(g(n))\Omega(g(n)).

Little-oh (o)(o): Non-tight Upper Bound
  • Definition: f(n)=o(g(n))f(n) = o(g(n)) if lim⁡n→∞f(n)g(n)=0\lim_{n \rightarrow \infty} \frac{f(n)}{g(n)} = 0.

  • Relationship: Indicates that f(n)f(n) becomes insignificant relative to g(n)g(n) as nn grows.

  • Example: n2=o(n3)n^2 = o(n^3).

Little-omega (ω)(\omega): Non-tight Lower Bound
  • Definition: f(n)=ω(g(n))f(n) = \omega(g(n)) if lim⁡n→∞g(n)f(n)=0\lim_{n \rightarrow \infty} \frac{g(n)}{f(n)} = 0.

Types of Analysis Cases

  • Worst Case: Provides an upper bound on running time. It serves as an absolute guarantee that the algorithm will not exceed this limit for any input.

  • Best Case: Provides a lower bound on running time. This describes the scenario where the algorithm runs at its fastest speed.

  • Average Case: Provides a prediction of the running time based on the assumption that input data is random. Any notation (O,Ω,ΘO, \Omega, \Theta) can mathematically represent any of these cases, but they are conceptually distinct.

Rules for Asymptotic Analysis

  1. Drop constants: 5n25n^2 becomes O(n2)O(n^2).

  2. Drop lower order terms: n2+n+5n^2 + n + 5 becomes O(n2)O(n^2).

  3. Polynomials vs Logarithms: Any polynomial dominates any logarithm.

  4. Exponentials vs Polynomials: Exponential functions dominate polynomials.

  5. Log Base: In algorithm analysis, "log" typically refers to log⁡2\log_2 unless specified otherwise.