My Notes

Study Timer
25:00
Today: 0 min
Total: 0 min
🏆

Achievement Unlocked!

Description

+50 XP

Design and Analysis of Algorithm 2022

Reading Timer
25:00
MIT121: Design and Analysis of Algorithms - Complete Solutions

MIT121: Design and Analysis of Algorithms

Purbanchal University | M.I.T. Second Semester Final Exam 2022
Complete Solutions with Detailed Explanations

Group A (Answer TWO Questions)

Question 1: Divide and Conquer & Binary Search 12 Marks

a) Divide and Conquer Approach (3 Marks)

Divide and Conquer is a powerful algorithmic paradigm that solves problems by breaking them down into smaller, more manageable sub-problems, solving each sub-problem independently, and then combining their solutions to solve the original problem [^1^].

Divide and Conquer                     Algorithm

Figure 1: Divide and Conquer Approach Workflow

The three main steps are:

  1. Divide: Break the original problem into smaller sub-problems that represent parts of the overall problem.
  2. Conquer: Solve each sub-problem recursively. If a sub-problem is small enough (base case), solve it directly.
  3. Combine/Merge: Merge the solutions of sub-problems to get the solution to the original problem.
Key Characteristic: Divide and Conquer works best when sub-problems are independent (non-overlapping). If sub-problems overlap, Dynamic Programming is more suitable.

b) Binary Search - Recursive Approach (6 Marks)

Algorithm:

BinarySearch(A, low, high, key): if low > high: return -1 // Element not found mid = (low + high) / 2 if A[mid] == key: return mid else if A[mid] > key: return BinarySearch(A, low, mid-1, key) else: return BinarySearch(A, mid+1, high, key)
Binary Search                     Visualization

Figure 2: Binary Search Step-by-Step Process

Recurrence Relation:

T(n) = T(n/2) + O(1)

Where:

  • T(n/2) = Time to search in half of the array
  • O(1) = Constant time for comparison and mid calculation

Complexity Derivation using Backward Substitution:

T(n) = T(n/2) + c
T(n/2) = T(n/4) + c
T(n/4) = T(n/8) + c
...
T(n/2k) = T(1) + c

Substituting back:
T(n) = T(n/2k) + k·c

When n/2k = 1, we have k = log₂n

Therefore: T(n) = T(1) + c·log₂n = O(log n)

Using Master Theorem [^3^]: a=1, b=2, f(n)=O(1)=O(n⁰)
logba = log₂1 = 0
Since f(n) = Θ(nlogba), Case 2 applies: T(n) = Θ(log n)

c) Trace: Searching 29 in Array [5, 7, 9, 14, 21, 29, 33, 46, 64, 71] (3 Marks)

Step Low High Mid A[Mid] Comparison Action
1 0 9 4 21 29 > 21 Search right half
2 5 9 7 46 29 < 46 Search left half
3 5 6 5 29 29 == 29 Found at index 5!
Result: Element 29 found at index 5 (0-based indexing) after 3 comparisons.

Question 2: Dynamic Programming & Travelling Salesman Problem 12 Marks

a) What is Dynamic Programming? (2 Marks)

Dynamic Programming (DP) is an optimization technique used to solve complex problems by breaking them down into overlapping sub-problems, solving each sub-problem only once, and storing the results to avoid redundant computations [^9^].

Key Properties:

  • Optimal Substructure: Optimal solution can be constructed from optimal solutions to sub-problems
  • Overlapping Sub-problems: Same sub-problems are solved multiple times

b) DP vs Divide and Conquer (2 Marks)

DP vs Divide and                     Conquer

Figure 3: Comparison of DP and Divide & Conquer Approaches

Aspect Divide and Conquer Dynamic Programming
Sub-problems Independent (non-overlapping) Overlapping sub-problems
Approach Top-down (recursive) Bottom-up (iterative) or Top-down with memoization
Storage No storage of results Stores results in table (memoization/tabulation)
Examples Merge Sort, Quick Sort, Binary Search Fibonacci, Knapsack, TSP, LCS
Key Difference: While both use the concept of breaking problems into sub-problems, DP is used when sub-problems overlap (same sub-problems solved multiple times), whereas Divide and Conquer is for independent sub-problems.

c) Travelling Salesman Problem (TSP) (6 Marks)

Problem Statement: Given a set of cities and distances between every pair of cities, find the shortest possible route that visits every city exactly once and returns to the starting point.

TSP Dynamic                     Programming

Figure 4: Travelling Salesman Problem Graph Example

Example Graph (4 cities):

Cost Matrix:
      0   10   15   20
     10    0   35   25
     15   35    0   30
     20   25   30    0
(City 0 to 3)

DP Approach:

Let dp[mask][i] = minimum cost to visit all cities in 'mask' ending at city 'i'

TSP_DP(cost): n = number of cities dp[2^n][n] initialized to infinity dp[1][0] = 0 // Starting at city 0 with only city 0 visited for mask from 1 to 2^n - 1: for last = 0 to n-1: if not (mask & (1 << last)): continue for nxt=0 to n-1: if mask & (1 << nxt): continue new_mask=mask | (1 << nxt) dp[new_mask][nxt]=min(dp[new_mask][nxt], dp[mask][last] + cost[last][nxt]) // Return to starting city ans=infinity for i=1 to n-1: ans=min(ans, dp[2^n - 1][i] + cost[i][0]) return ans

Time Complexity: O(n² × 2ⁿ)
Space Complexity: O(n × 2ⁿ)

Solution for example: 0 → 1 → 3 → 2 → 0 = 10 + 25 + 30 + 15 = 80

Question 3: Greedy Algorithms & Knapsack Problem 12 Marks

a) Optimization Problems & Greedy Approach (4 Marks)

Optimization Problems: Problems where we seek to find the best solution from all feasible solutions, either maximizing or minimizing an objective function subject to constraints.

Why Greedy Approach?

  1. Local Optimal Choice: Makes the choice that looks best at the moment
  2. Efficiency: Usually faster than DP (often O(n log n) or O(n))
  3. Simplicity: Easier to implement and understand
  4. No Backtracking: Once a choice is made, it's never reconsidered
Important: Greedy approach works only when the problem exhibits Greedy Choice Property (global optimum can be reached by choosing local optimum) and Optimal Substructure.

b) Job Sequencing with Deadline (2 Marks)

Job Sequencing

Figure 5: Job Sequencing with Deadline Example

Problem: Given n jobs with deadlines and profits, schedule jobs to maximize profit such that each job is completed before its deadline. Each job takes unit time.

Greedy Strategy:

  1. Sort jobs in decreasing order of profit
  2. For each job, assign it to the latest available slot before its deadline
  3. If no slot is available, skip the job

c) Knapsack Problem Solution (6 Marks)

Greedy                         Knapsack

Figure 6: Fractional Knapsack using Greedy Approach

Given Data:

Item 1 2 3 4 5
Profit ($) 25 20 15 40 50
Weight (kg) 3 2 1 4 5

Knapsack Capacity: 6 kg

Step 1: Calculate Profit/Weight Ratio

Item Profit Weight Ratio (P/W)
1 25 3 8.33
2 20 2 10.00
3 15 1 15.00
4 40 4 10.00
5 50 5 10.00

Step 2: Sort by Ratio (Descending)

Item 3 (15.0) → Item 2 (10.0) → Item 4 (10.0) → Item 5 (10.0) → Item 1 (8.33)

Step 3: Fill Knapsack

Item Weight Remaining Capacity Profit Added Total Profit
3 1 6 - 1 = 5 15 15
2 2 5 - 2 = 3 20 35
4 3 (partial) 3 - 3 = 0 40 × (3/4) = 30 65
Final Answer:
Items selected: 3 (full), 2 (full), 4 (3/4 fraction)
Total Weight: 1 + 2 + 3 = 6 kg
Maximum Profit: $65

Group B (Answer SIX Questions)

Question 4: RAM Model & Theta Notation 6 Marks

a) RAM Model (3 Marks)

RAM                         Model

Figure 7: Random Access Machine (RAM) Model

The Random Access Machine (RAM) model is a theoretical model of computation used to analyze algorithms independent of hardware [^2^].

Key Components:

  • Memory: Infinite array of cells, each holding an integer or address
  • CPU: Single processor executing one instruction at a time
  • Random Access: Any memory cell can be accessed in O(1) time

Assumptions:

  1. Each basic operation (+, -, *, /, comparison, assignment) takes unit time O(1)
  2. Memory access (read/write) takes O(1) time
  3. No memory hierarchy (cache vs main memory distinction ignored)
  4. Sequential execution (no parallelism)

Why RAM Model? It provides a standardized way to analyze algorithm complexity that is independent of specific hardware, programming language, or implementation details.

b) Theta (Θ) Notation (3 Marks)

Theta                         Notation

Figure 8: Asymptotic Notations - Big O, Omega, and Theta

Definition: Θ(g(n)) = {f(n): there exist positive constants c₁, c₂ and n₀ such that 0 ≤ c₁·g(n) ≤ f(n) ≤ c₂·g(n) for all n ≥ n₀}

Theta Notation                         Graph

Figure 9: Geometrical Interpretation of Theta Notation

Geometrical Interpretation:

Theta notation provides both upper and lower bounds on the growth rate of a function. Graphically, f(n) is Θ(g(n)) if f(n) lies between c₁·g(n) and c₂·g(n) for all n ≥ n₀.

Interpretation:
• f(n) is "sandwiched" between two constant multiples of g(n)
• g(n) is an asymptotically tight bound for f(n)
• f(n) grows at the same rate as g(n)

Example: 3n² + 5n + 2 = Θ(n²) because for n ≥ 1:
c₁·n² ≤ 3n² + 5n + 2 ≤ c₂·n² (where c₁ = 3, c₂ = 10)

Question 5: Quick Sort Algorithm 6 Marks

Quick Sort Algorithm

Quick                         Sort

Figure 10: Quick Sort Partition and Recursive Sorting

Algorithm:

QuickSort(A, low, high): if low < high: pivot_index=Partition(A, low, high) QuickSort(A, low, pivot_index - 1) QuickSort(A, pivot_index + 1, high) Partition(A, low, high): pivot=A[high] i=low - 1 for j=low to high - 1: if A[j] <=pivot: i=i + 1 swap A[i] and A[j] swap A[i + 1] and A[high] return i + 1

Complexity Analysis

Case Time Complexity Condition
Best Case Ω(n log n) Pivot divides array into two equal halves
Average Case Θ(n log n) Pivot divides array into reasonably balanced parts
Worst Case O(n²) Pivot is always smallest or largest element (sorted array)

Derivation:

Best/Average Case:
T(n) = 2T(n/2) + O(n)
Using Master Theorem: a=2, b=2, f(n)=O(n)
log₂2 = 1, so nlog₂2 = n¹ = n
Case 2: T(n) = Θ(n log n)

Worst Case:
T(n) = T(n-1) + O(n)
= T(n-1) + cn
= cn + c(n-1) + c(n-2) + ... + c(1)
= c(n(n+1)/2) = O(n²)

Space Complexity: O(log n) best case (balanced recursion), O(n) worst case (unbalanced recursion) [^6^]

Question 6: Master Theorem Applications 6 Marks

Master Theorem: For T(n) = aT(n/b) + f(n) where a ≥ 1, b > 1 [^3^]

Compare f(n) with nlogba:
Case 1: If f(n) = O(nlogba - ε), then T(n) = Θ(nlogba)
Case 2: If f(n) = Θ(nlogba), then T(n) = Θ(nlogba log n)
Case 3: If f(n) = Ω(nlogba + ε), then T(n) = Θ(f(n))

(i) T(n) = 2T(n/2) + n³

a = 2, b = 2, f(n) = n³
nlogba = nlog₂2 = n¹ = n
Compare: n³ vs n → f(n) is polynomially larger
Case 3 applies: T(n) = Θ(n³)

(ii) T(n) = 25T(n/5) + 5n²

a = 25, b = 5, f(n) = 5n²
nlogba = nlog₅25 = n²
Compare: 5n² vs n² → f(n) = Θ(nlogba)
Case 2 applies: T(n) = Θ(n² log n)

(iii) T(n) = T(n-1) + n

Note: This recurrence is NOT in the form T(n) = aT(n/b) + f(n) required by Master Theorem (it's not divide and conquer, it's decrease and conquer).

Using backward substitution:
T(n) = T(n-1) + n
T(n-1) = T(n-2) + (n-1)
...
T(n) = n + (n-1) + (n-2) + ... + 1 = n(n+1)/2
T(n) = Θ(n²)

Question 7: Chinese Remainder Theorem 6 Marks

Given System:

x ≡ 2 (mod 5)
x ≡ 3 (mod 7)
x ≡ 10 (mod 11)

Solution using CRT [^7^]:

Step 1: Calculate M = 5 × 7 × 11 = 385

Step 2: Calculate M₁, M₂, M₃

  • M₁ = M/5 = 385/5 = 77
  • M₂ = M/7 = 385/7 = 55
  • M₃ = M/11 = 385/11 = 35

Step 3: Find modular inverses y₁, y₂, y₃

  • y₁ = M₁⁻¹ (mod 5) = 77⁻¹ (mod 5) = 2⁻¹ (mod 5) = 3 (since 2×3=6≡1 mod 5)
  • y₂ = M₂⁻¹ (mod 7) = 55⁻¹ (mod 7) = 6⁻¹ (mod 7) = 6 (since 6×6=36≡1 mod 7)
  • y₃ = M₃⁻¹ (mod 11) = 35⁻¹ (mod 11) = 2⁻¹ (mod 11) = 6 (since 2×6=12≡1 mod 11)

Step 4: Calculate x

x = (a₁M₁y₁ + a₂M₂y₂ + a₃M₃y₃) mod M
x = (2×77×3 + 3×55×6 + 10×35×6) mod 385
x = (462 + 990 + 2100) mod 385
x = 3552 mod 385
x = 3552 - 9×385 = 3552 - 3465 = 87
Answer: x ≡ 87 (mod 385)
Smallest positive solution: x = 87

Verification:
87 ÷ 5 = 17 remainder 2 ✓
87 ÷ 7 = 12 remainder 3 ✓
87 ÷ 11 = 7 remainder 10 ✓

Question 8: Prim's Algorithm 6 Marks

a) Why Prim's Algorithm is Not Suitable for Disconnected Graphs (2 Marks)

Prim's algorithm starts from a single vertex and grows the MST by adding the minimum weight edge that connects a vertex in the MST to a vertex outside it. If the graph is disconnected, Prim's algorithm will:

  • Only find the MST for the connected component containing the starting vertex
  • Never reach vertices in other connected components
  • Result in a forest rather than a single spanning tree

A spanning tree by definition must connect all vertices. For disconnected graphs, we need to find a Minimum Spanning Forest (MSF) instead.

b) Trace Prim's Algorithm on Given Graph (4 Marks)

Prim's                             Algorithm

Figure 11: Prim's Algorithm Step-by-Step Execution

Graph Analysis:

Vertices: a, b, c, d, e, f, g
Starting from vertex 'a'

Step MST Vertices Candidate Edges Min Edge Weight Total Weight
1 {a} a-b(5), a-c(3) a-c 3 3
2 {a,c} a-b(5), c-b(4), c-d(5), c-f(6) c-b 4 7
3 {a,c,b} a-b(5), b-e(2), b-d(6), c-d(5), c-f(6) b-e 2 9
4 {a,c,b,e} b-d(6), c-d(5), c-f(6), e-d(6), e-f(3), e-g(5) e-f 3 12
5 {a,c,b,e,f} c-d(5), e-d(6), f-d(6), f-g(4) f-g 4 16
6 {a,c,b,e,f,g} c-d(5), e-d(6), f-d(6) c-d 5 21
MST Edges: a-c(3), c-b(4), b-e(2), e-f(3), f-g(4), c-d(5)
Total Weight: 21

Question 9: Complexity Classes 6 Marks

Complexity                             Classes

Figure 12: Complexity Classes - P, NP, NP-Complete, and NP-Hard

Major Complexity Classes:

1. Class P (Polynomial Time)

  • Problems solvable in polynomial time O(nk) by deterministic algorithms
  • Considered "tractable" or "efficiently solvable"
  • Examples: Sorting, Searching, MST, Shortest Path

2. Class NP (Nondeterministic Polynomial Time)

  • Problems where a proposed solution can be verified in polynomial time
  • P ⊆ NP (all problems in P are also in NP)
  • Examples: TSP (decision), Knapsack (decision), Graph Coloring

3. NP-Complete (NPC)

  • Problems that are both in NP and NP-Hard
  • If any NP-Complete problem can be solved in polynomial time, then P = NP
  • First problem proven NP-Complete: SAT (Satisfiability)
  • Examples: 3-SAT, Clique, Vertex Cover, Hamiltonian Cycle

4. NP-Hard

  • Problems at least as hard as the hardest problems in NP
  • May not be in NP (need not have polynomial-time verifiable solutions)
  • Examples: Halting Problem, TSP (optimization), Chess
Complexity Venn                             Diagram

Figure 13: Relationship Between Complexity Classes

The P vs NP Problem: The most important open problem in computer science. If P = NP, then every problem whose solution can be quickly verified can also be quickly solved. Most researchers believe P ≠ NP.

Question 10: 0/1 Knapsack using Dynamic Programming 6 Marks

Problem: Given n items with weights wt[] and values val[], and a knapsack of capacity W, find the maximum value that can be obtained without exceeding capacity. Each item can be taken at most once (0/1 property).

0/1 Knapsack DP                             Table

Figure 14: 0/1 Knapsack DP Table Construction

DP Approach:

State Definition:
dp[i][w] = Maximum value achievable using first i items with capacity w

Recurrence Relation:

dp[i][w] = max(
    dp[i-1][w], // Don't take item i
    val[i-1] + dp[i-1][w-wt[i-1]] // Take item i (if wt[i-1] ≤ w)
)

Base Cases:

  • dp[0][w] = 0 (no items, no value)
  • dp[i][0] = 0 (no capacity, no value)
0/1-KNAPSACK(W, val, wt, n): // Create DP table dp[n+1][W+1] // Initialize for i = 0 to n: dp[i][0] = 0 for w = 0 to W: dp[0][w] = 0 // Fill table for i = 1 to n: for w = 1 to W: if wt[i-1] <= w: dp[i][w]=max(val[i-1] + dp[i-1][w-wt[i-1]], dp[i-1][w]) else: dp[i][w]=dp[i-1][w] return dp[n][W]

Complexity Analysis:

  • Time Complexity: O(n × W) - We fill a table of size (n+1) × (W+1)
  • Space Complexity: O(n × W) - For the DP table
Why not Greedy? Unlike Fractional Knapsack, 0/1 Knapsack cannot be solved optimally using greedy approach because items are indivisible. The greedy choice property doesn't hold - selecting the item with highest value/weight ratio first doesn't guarantee optimal solution [^8^].

Example Trace:

val = [60, 100, 120], wt = [10, 20, 30], W = 50

Optimal Solution: Select items 2 and 3 (weight 20+30=50, value 100+120=220)

End of Solutions

Best of luck with your exams!

Purbanchal University | M.I.T. | Design and Analysis of Algorithms