1 Foundation Of Algorithm Analysis

Design and Analysis of Algorithms · Unit 1 · 4 hrs

Foundation of Algorithm Analysis

Exam-focused notes for Foundation of Algorithm Analysis (Design and Analysis of Algorithms, CSC325): what the TU syllabus asks and how it has actually been tested, with 13 solved past questions from this unit.

Foundation of Algorithm Analysis in short

This unit sets up the vocabulary and machinery the rest of the course depends on: what an algorithm is, the RAM model used to count its steps, the time and space measures built on that count, aggregate analysis for a sequence of operations, the asymptotic notations that describe growth, and the recurrence relations that recursive algorithms produce together with the three standard techniques for solving them.

Foundation of Algorithm Analysis: notes

Algorithm and its properties

An algorithm is a finite set of unambiguous instructions that takes some value(s) as input, performs a well-defined computation, and produces value(s) as output in a finite amount of time. A procedure only qualifies as an algorithm if it satisfies the following properties: input/output (it accepts zero or more inputs and produces at least one output), correctness (it produces the output required by the problem statement for every valid input), finiteness (it terminates after a finite number of steps, never looping forever), feasibility (every instruction is basic enough to be carried out, in principle by hand, in finite time), flexibility (it can be modified or extended without a full redesign), and efficiency (it uses as little running time and memory as the problem allows). An algorithm is distinct from a program: the algorithm is the language-independent idea, the program is its expression in a particular programming language.

RAM model

The Random Access Machine (RAM) model is the abstract machine used to count the number of steps an algorithm performs, independent of any real processor's clock speed or instruction set. Under the RAM model, each simple arithmetic operation ($+$, $-$, $\times$, $/$), comparison, assignment, and memory reference (reading or writing a variable or array cell) costs exactly one step, and every word is assumed large enough to hold any value the algorithm manipulates, so a single word operation is $O(1)$ regardless of the magnitude of the number stored. Control constructs such as loops and function calls are not themselves basic operations; their cost is the sum of the costs of the statements they execute, counted once per execution. This uniform-cost assumption is what allows time complexity to be expressed as a function of the input size $n$ alone, rather than of the underlying hardware.

Time and Space Complexity

The time complexity of an algorithm is the number of elementary steps, as counted under the RAM model, that it performs as a function of the input size $n$. The space complexity is the amount of memory, again counted as a function of $n$, that the algorithm needs to hold its input, output, and working variables. Because the exact step count depends on the particular input and not only on its size, complexity is reported for three cases: the best case is the minimum running time over all inputs of size $n$, a lower bound on how fast the algorithm can possibly run at that size; the worst case is the maximum running time over all inputs of size $n$, and is the figure normally quoted as "the" complexity because no input of that size can force the algorithm to run any slower; the average case is the expected running time over all inputs of size $n$, usually under a uniform probability assumption on the inputs.

Detailed analysis of algorithms (factorial)

Two rules of thumb keep the analysis of a piece of code manageable. First, statements that run in constant time regardless of $n$, assignments, printf, scanf, return, contribute only an additive constant and are neglected once a loop dominates the count. Second, the cost of loops is what matters:

  • A loop that runs from $1$ to $n$ incrementing by a fixed amount contributes $O(n)$.
  • Two such loops nested inside each other contribute the product of their individual costs, $O(n) \times O(n) = O(n^2)$.
  • A loop whose index is multiplied by a constant factor each iteration, for (i = 1; i <= n; i *= c), runs $O(\log_c n) = O(\log n)$ times, since the index takes only that many multiplications to reach $n$.

Applying this to a complete factorial program:

int main(void) {
    int i, n, fact = 1;
    printf("Enter n: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++)
        fact = fact * i;
    printf("Factorial = %d\n", fact);
    return 0;
}

counting under the RAM model: the prompt and the read are $1$ step each; the loop initialization i = 1 is $1$ step; the test i <= n runs once per iteration including the final failing test, so $n$ times; the increment i++ and the body fact = fact * i each run once per successful iteration, so $(n-1)$ times each; the final print and the return are $1$ step each. Summing,

$$ \begin{aligned} T(n) &= \underbrace{2}{\text{prompt, scanf}} + \underbrace{1}{i=1} + \underbrace{n}{i \le n} + \underbrace{(n-1)}{i++} + \underbrace{(n-1)}{\text{fact}=\text{fact}\times i} + \underbrace{2}{\text{print, return}} \ &= 3n + 3. \end{aligned} $$

So $T(n) = 3n + 3 = \Theta(n)$: linear in $n$, exactly as the informal "one loop, one pass" rule predicts. The space used is three words, for i, n, and fact, none of which grow with $n$, so the space complexity is $O(1)$.

What this unit covers

  • Algorithm and its properties
  • RAM model
  • Time and Space Complexity
  • detailed analysis of algorithms (Like factorial algorithm)
  • Concept of Aggregate Analysis
  • Asymptotic Notations: Big-O, Big-Ω and Big-Ө Notations their Geometrical Interpretation and Examples
  • Recurrences: Recursive Algorithms and Recurrence Relations
  • Solving Recurrences (Recursion Tree Method, Substitution Method, Application of Masters Theorem)

Solving Recurrences

2082 · 5 marks

Solve the recurrence relation T(n) = 2T(n/2) + n using recursion tree method. [5]

Show solved answer

Solving $T(n) = 2T(n/2) + n$ Using the Recursion Tree Method

Given

  • Recurrence: $T(n) = 2T\left(\dfrac{n}{2}\right) + n$
  • Branching factor: $a = 2$ (each node makes 2 recursive calls)
  • Subproblem shrink factor: $b = 2$ (size divided by 2)
  • Cost at a node of size $m$: $m$ (the "$+n$" term)
  • Base case: $T(1) = \Theta(1)$

Solution

Building the recursion tree

Level 0:            n                         cost = n
                  /   \
Level 1:       n/2     n/2                    cost = n/2 + n/2 = n
              /  \     /  \
Level 2:   n/4  n/4  n/4  n/4                 cost = 4·(n/4) = n
             ...        ...
Level k:  2^k nodes each of size n/2^k        cost = 2^k·(n/2^k) = n
             ...
Level log n: n leaves each of size 1          cost = n

Cost per level

Level $i$Number of nodesSize per nodeCost per level
0$1$$n$$n$
1$2$$n/2$$n$
2$4$$n/4$$n$
$i$$2^i$$n/2^i$$2^i \cdot \dfrac{n}{2^i} = n$
$\log_2 n$$n$$1$$n$

Key observation: Every level contributes exactly $n$.

Number of levels

The recursion stops when the subproblem size reaches 1:

$$\frac{n}{2^k} = 1 \implies 2^k = n \implies k = \log_2 n$$

Number of levels $= \log_2 n + 1$ (levels $0$ through $\log_2 n$).

Summing all levels

$$T(n) = \sum_{i=0}^{\log_2 n} n = n ,(\log_2 n + 1) = n\log_2 n + n$$

Final result

$$\boxed{T(n) = \Theta(n \log n)}$$

This matches the complexity of Merge Sort, which obeys the same recurrence.

Open this answer on its own page →

2081 · 5 marks

Solve the following recurrence relations using master's method.

  1. $T(n) = 2T\left(\frac{n}{2}\right) + n^3,\ n > 1;\quad T(n) = 1,\ n = 1$

  2. $T(n) = 2T\left(\frac{n}{4}\right) + 1,\ n > 1;\quad T(n) = 1,\ n = 1$

[5]

Show solved answer

Solving Recurrence Relations Using Master's Method

Master Method Framework

For $T(n) = aT\left(\frac{n}{b}\right) + f(n)$ with $a \geq 1$, $b > 1$:

Compute the critical exponent $\log_b a$ and compare $f(n)$ with $n^{\log_b a}$:

CaseConditionResult
1$f(n) = O(n^{\log_b a - \epsilon})$, $\epsilon > 0$$T(n) = \Theta(n^{\log_b a})$
2$f(n) = \Theta(n^{\log_b a})$$T(n) = \Theta(n^{\log_b a}\log n)$
3$f(n) = \Omega(n^{\log_b a + \epsilon})$, $\epsilon > 0$ (+ regularity)$T(n) = \Theta(f(n))$

Given Data

  • Recurrence 1: $T(n) = 2T(n/2) + n^3$, $n>1$; $T(1)=1$
  • Recurrence 2: $T(n) = 2T(n/4) + 1$, $n>1$; $T(1)=1$

Problem 1: $T(n) = 2T\left(\dfrac{n}{2}\right) + n^3$

Parameters: $a = 2,\ b = 2,\ f(n) = n^3$

Critical exponent: $$\log_b a = \log_2 2 = 1 \implies n^{\log_b a} = n$$

Compare: $f(n) = n^3$ vs $n^1$

Since $n^3 = \Omega(n^{1+\epsilon})$ with $\epsilon = 2 > 0$, this is Case 3.

Regularity check: $$a,f!\left(\frac{n}{b}\right) = 2\left(\frac{n}{2}\right)^3 = \frac{n^3}{4} \leq c,n^3,\quad c=\tfrac14 < 1 \ \checkmark$$

Result: $$\boxed{T(n) = \Theta(n^3)}$$


Problem 2: $T(n) = 2T\left(\dfrac{n}{4}\right) + 1$

Parameters: $a = 2,\ b = 4,\ f(n) = 1 = n^0$

Critical exponent: $$\log_b a = \log_4 2 = \frac{1}{2} \implies n^{\log_b a} = \sqrt{n}$$

Compare: $f(n) = n^0$ vs $n^{1/2}$

Since $n^0 = O(n^{1/2 - \epsilon})$ with $\epsilon = \tfrac12 > 0$, this is Case 1.

Result: $$\boxed{T(n) = \Theta(\sqrt{n})}$$


Summary

Recurrence$\log_b a$$f(n)$CaseSolution
$2T(n/2)+n^3$$1$$n^3$3$\Theta(n^3)$
$2T(n/4)+1$$1/2$$1$1$\Theta(\sqrt{n})$
Open this answer on its own page →

2080

Recurrence Relations and Solving using Substitution Method

A recurrence relation is an equation or inequality that describes a function in terms of its values on smaller inputs. To solve a recurrence relation means to obtain a function defined on the natural numbers that satisfies the recurrence. When we analyze recursive algorithms, we express their run...

Open this answer on its own page →

2079 · 5 marks

Solve the following recurrence relations using masters method.

a. $T(n) = 2T(n/4) + kn^2,\ n > 1;\ T(1) = 1$

b. $T(n) = 5T(n/4) + kn,\ n > 1;\ T(1) = 1$

[5]

For $T(n) = aT(n/b) + f(n)$ with $a \geq 1$, $b 1$, compare $f(n)$ with $n^{\logb a}$: - Case 1: $f(n) = O(n^{\logb a - \epsilon})$ $\Rightarrow$ $T(n) = \Theta(n^{\logb a})$ - Case 2: $f(n) = \Theta(n^{\logb a})$ $\Rightarrow$ $T(n) = \Theta(n^{\logb a}\log n)$ - Case 3:

Open this answer on its own page →

2078 · 5 marks

Explain the recursion tree method for solving the recurrence relation. Solve following recurrence relation using this method. T(n)=2T(n/2) +1 for n>1, T(n)=1 for n=1 [5]

Show solved answer

Recursion Tree Method for Solving Recurrence Relations

Explanation of the Recursion Tree Method

The recursion tree method is a technique for solving recurrence relations by expanding the recurrence into a tree. Each node represents the cost incurred at a subproblem, and the children of a node represent the recursive subproblems generated. The total cost is found by:

  1. Expanding the recurrence into a tree, level by level.
  2. Computing the cost contributed at each level.
  3. Finding the height (number of levels) of the tree by determining when the subproblem size reaches the base case.
  4. Summing the per-level costs across all levels.
  5. Expressing the total as a closed form / Big-Oh bound.

Given Data

  • Recurrence: $T(n) = 2T(n/2) + 1$ for $n > 1$
  • Base case: $T(1) = 1$
  • Non-recursive (combine) cost per call: $1$
  • Branching factor: $2$, subproblem size scaling: $n/2$

Step 1: Draw the Recursion Tree

Level 0:            T(n)                       cost = 1
                  /      \
Level 1:      T(n/2)    T(n/2)                 cost = 2×1 = 2
             /   \       /   \
Level 2: T(n/4) T(n/4) T(n/4) T(n/4)           cost = 4×1 = 4
                    ...
Level k:  2^k nodes, each of size n/2^k        cost = 2^k

Step 2: Cost at Each Level

Level $i$Number of nodesCost per nodeLevel cost
0$1$$1$$1$
1$2$$1$$2$
2$4$$1$$4$
$i$$2^i$$1$$2^i$

Step 3: Height of the Tree

Recursion stops when subproblem size reaches the base case $n/2^k = 1$:

$$2^k = n \implies k = \log_2 n$$

So there are levels $0, 1, \dots, \log_2 n$, i.e. $\log_2 n + 1$ levels.

Note: at the last level, the $2^{\log_2 n} = n$ leaves each have $T(1) = 1$, contributing $n$, which is consistent with the internal-node accounting below.

Step 4: Sum the Total Cost

$$T(n) = \sum_{i=0}^{\log_2 n} 2^i$$

This is a geometric series with ratio $2$:

$$T(n) = \frac{2^{\log_2 n + 1} - 1}{2 - 1} = 2^{\log_2 n + 1} - 1 = 2\cdot 2^{\log_2 n} - 1$$

Since $2^{\log_2 n} = n$:

$$T(n) = 2n - 1$$

Step 5: Big-Oh Notation

$$\boxed{T(n) = 2n - 1 = O(n)}$$


Verification (Master Theorem)

For $T(n)=aT(n/b)+f(n)$ with $a=2,\ b=2,\ f(n)=1=\Theta(n^0)$: $$n^{\log_b a} = n^{\log_2 2} = n^1 = n$$ Since $f(n) = O(n^{1-\varepsilon})$, Case 1 applies, giving $T(n) = \Theta(n^{\log_b a}) = \Theta(n)$. This confirms $O(n)$.

Conclusion

Using the recursion tree method, $T(n) = 2T(n/2) + 1$ solves to $T(n) = 2n - 1 = O(n)$, matching the Master Theorem result.

Open this answer on its own page →

2076 · 5 marks

Solve the following recurrence relation using the master method.

a. $T(n) = 7 T(n/2) + n^2$

b. $T(n) = 4 T(n/4) + kn$

[5]

  • Part a: $T(n) = 7T(n/2) + n^2$ - Part b: $T(n) = 4T(n/4) + kn$ (where $k$ is a positive constant) For a recurrence $T(n) = aT(n/b) + f(n)$ with $a \geq 1$, $b 1$, compare $f(n)$ with $n^{\logb a}$: Case Condition Result ------------------------- 1 $f(n) = O(n^{\logb a - \epsilon})$, some
Open this answer on its own page →

Asymptotic Notations

2081 · 5 marks

Write short notes on: a) Big Oh, Big Omega, Big theta b) Class P, Class NP and NP-Complete [5]

Show solved answer

Short Notes: Asymptotic Notations and Complexity Classes


a) Big Oh, Big Omega, and Big Theta

Big Oh O(g(n)) - Asymptotic Upper Bound

Big Oh notation gives the asymptotic upper bound of a function.

Definition: A function f(x) is said to be O(g(x)) if and only if there exist two positive constants c and x₀ such that:

For all x >= x₀ : f(x) <= c * g(x)

This means g(n) is the upper bound of f(n). The algorithm will never take more time than this bound.

Example: If f(n) = 3n² + 4n + 1, then:

  • 3n² + 4n + 1 <= 14n² for all n >= 1
  • Therefore, f(n) = O(n²) with c = 14, x₀ = 1

Big Omega Ω(g(n)) - Asymptotic Lower Bound

Big Omega notation gives the asymptotic lower bound of a function.

Definition: A function f(x) is said to be Ω(g(x)) if and only if there exist two positive constants c and x₀ such that:

For all x >= x₀ : f(x) >= c * g(x)

This means g(n) is the lower bound of f(n).

Example: If f(n) = 3n² + 4n + 1, then:

  • 3n² + 4n + 1 >= 3n² for all n >= 1
  • Therefore, f(n) = Ω(n²) with c = 3, x₀ = 1

Big Theta Θ(g(n)) - Asymptotic Tight Bound

Big Theta notation gives the asymptotically tight bound of a function.

Definition: A function f(x) is said to be Θ(g(x)) if and only if there exist three positive constants c₁, c₂ and x₀ such that:

For all x >= x₀ : c₁ * g(x) <= f(x) <= c₂ * g(x)

This means g(n) is both an upper and lower bound of f(n).

Example: If f(n) = 3n² + 4n + 1, g(n) = n², choose c₁ = 1, c₂ = 14, n₀ = 1:

  • 1 * n² <= 3n² + 4n + 1 <= 14 * n² for all n >= 1
  • Therefore, f(n) = Θ(n²)

b) Class P, Class NP, and NP-Complete

Class P (Polynomial Time)

  • Class P is the set of all decision problems that can be solved by a deterministic algorithm in polynomial time O(n^k) for some constant k.
  • These are considered tractable (efficiently solvable) problems.
  • Examples: Sorting, searching, shortest path (Dijkstra's), GCD computation.

Class NP (Non-deterministic Polynomial Time)

  • Class NP is the set of all decision problems for which a given solution (certificate) can be verified in polynomial time by a deterministic algorithm.
  • NP does not necessarily mean the problem cannot be solved in polynomial time; it means verification is polynomial.
  • Every problem in P is also in NP (P ⊆ NP), but whether P = NP is an unsolved problem in computer science.
  • Examples: Boolean satisfiability (SAT), Hamiltonian cycle, Subset sum.

NP-Complete

  • A problem X is NP-Complete if:

    1. X belongs to NP (its solution can be verified in polynomial time), AND
    2. Every other problem in NP can be reduced to X in polynomial time (X is NP-Hard).
  • NP-Complete problems are the hardest problems in NP.

  • If any NP-Complete problem can be solved in polynomial time, then all NP problems can be solved in polynomial time (i.e., P = NP).

  • Examples: SAT problem, Travelling Salesman Problem (TSP), Knapsack problem, Graph Coloring.


Relationship Summary

P ⊆ NP
NP-Complete ⊆ NP
If P = NP, then all NP-Complete problems become P
ClassSolvable in Poly Time?Verifiable in Poly Time?
PYesYes
NPUnknown (maybe)Yes
NP-CompleteUnknownYes
Open this answer on its own page →

2076 · 10 marks

What do you mean by the complexity of an algorithm? Explain the asymptotic notations used to describe the time/space complexity of any algorithm with their geometrical interpretation and example.[10]

Algorithm complexity is a measure of the amount of time and/or space (memory) required by an algorithm as a function of the input size n. - Time Complexity -- the number of basic operations performed as a function of input size n (using the RAM model, where basic operations like +, -, , / each co...

Open this answer on its own page →

RAM model

2080 · 5 marks

Define RAM model. Write down iterative algorithm for finding factorial and provide its detailed analysis. [5]

Definition: The Random Access Machine (RAM) model is a model for counting the steps in an algorithm in order to analyze its time complexity. In this model: - Basic operations (+, -, , /) are counted as 1 step - Memory references (read/write) are counted as 1 step - Loops and function calls are no...

Open this answer on its own page →

2078 · 10 marks

What are the elementary properties of algorithm? Explain. Why do you need algorithm? Discuss about analysis of the RAM model for analysis of algorithm with suitable example.[10]

--- An algorithm is a finite set of instructions where each instruction can be executed in finite time to perform computation by taking some value as input and to produce value(s) as output. The following are the elementary properties (characteristics) of an algorithm: - An algorithm must take on...

Open this answer on its own page →

Concept of Aggregate Analysis

2080 · 5 marks

Write short notes on a) Aggregate Analysis b) Selection problems [5]

Definition: Aggregate analysis is a technique used in amortized analysis that determines the upper bound T(n) on the total cost of a sequence of n operations, then calculates the average (amortized) cost per operation as T(n)/n. Steps in Aggregate Analysis: 1. Show that a sequence of n operations...

Open this answer on its own page →

Time and Space Complexity

2079 · 5 marks

Write short notes on: a) Best, Worst and average case complexity b) Greedy Strategy [5]

--- When analyzing an algorithm, the running time often depends not just on the size of the input but also on the particular instance of the input. To capture this, we define three cases: --- - It gives the lower bound on the running time of the algorithm for any instance of input. - This indicat...

Open this answer on its own page →

detailed analysis of algorithms

2078 · 5 marks

Write an algorithm to find the maximum element of an array and analyze its time complexity. [5]

An algorithm is a finite set of instructions where each instruction can be executed in finite time, taking input value(s) and producing output value(s). The iterative approach is used here to find the maximum element. --- Input: Array A of n elements (index 0 to n-1) Output: Maximum element of th...

Open this answer on its own page →