Every control abstraction, problem algorithm, and exam-ready complexity analysis below is written in clean, intent-first style—easy to memorize and directly usable in KTU exams.
1. Divide & Conquer (Module 2)
Control Abstraction
Algorithm DivideAndConquer(Problem)
{
if IsSmall(Problem) then return SolveDirectly(Problem);
Split Problem into P1, P2, ..., Pk;
for i = 1 to k do
Ans[i] = DivideAndConquer(Pi);
return Combine(Ans[1..k]);
}
Problem 1A: 2-Way Merge Sort
Algorithm MergeSort(A, low, high)
{
if low < high then
{
mid = (low + high) / 2;
MergeSort(A, low, mid); // Sort left half
MergeSort(A, mid + 1, high); // Sort right half
Merge(A, low, mid, high); // Combine sorted halves
}
}
Algorithm Merge(A, low, mid, high)
{
i = low; j = mid + 1; k = low;
while (i <= mid) and (j <= high) do
{
if A[i] <= A[j] then Temp[k++] = A[i++];
else Temp[k++] = A[j++];
}
while (i <= mid) do Temp[k++] = A[i++];
while (j <= high) do Temp[k++] = A[j++];
Copy Temp[low..high] back into A[low..high];
}
Analysis:
- Divide: Finding
mid takes O(1).
- Conquer: 2 recursive calls on subarrays of size n/2⟹2T(n/2).
- Combine:
Merge() scans n elements once ⟹Θ(n).
- Recurrence: T(n)=2T(n/2)+Θ(n).
- Master's Theorem: a=2,b=2,k=1,p=0⟹a=bk (Case 2) ⟹ Time = Θ(nlogn) (Best, Average, and Worst case).
- Space Complexity: O(n) auxiliary (for
Temp[] array) + O(logn) recursion stack.
Problem 1B: Strassen's Matrix Multiplication
Algorithm Strassen(A, B, n)
{
if n == 1 then return A[1][1] * B[1][1];
Partition A and B into four (n/2 x n/2) submatrices;
Compute 7 products P1..P7 recursively using Strassen();
Compute C11, C12, C21, C22 from P1..P7 using additions/subtractions;
return Combined Matrix C;
}
Analysis:
- Conquer: 7 recursive multiplications of size n/2⟹7T(n/2) (replaces 8 in naive D&C).
- Combine: 18 matrix additions/subtractions of size n/2×n/2⟹Θ(n2).
- Recurrence: T(n)=7T(n/2)+Θ(n2).
- Master's Theorem: a=7,b=2,k=2⟹a>bk (7>4, Case 1) ⟹ Time = Θ(nlog27)≈Θ(n2.81).
- Space Complexity: O(n2) auxiliary (for intermediate submatrices across recursion).
(See Strassen.md for the 7 product formulas and memory guide.)
2. Greedy Strategy (Module 3)
Control Abstraction
Algorithm Greedy(Inputs, n)
{
Solution = Empty;
for i = 1 to n do
{
x = PickBestChoice(Inputs);
if IsFeasible(Solution, x) then Add x to Solution;
}
return Solution;
}
Problem 2A: Fractional Knapsack
Algorithm FractionalKnapsack(Profit[], Weight[], Capacity, n)
{
Sort all items in descending order of (Profit[i] / Weight[i]);
TotalProfit = 0;
Remaining = Capacity;
for i = 1 to n do
{
if Weight[i] <= Remaining then
{
TotalProfit += Profit[i];
Remaining -= Weight[i];
}
else
{
Fraction = Remaining / Weight[i];
TotalProfit += Profit[i] * Fraction;
break;
}
}
return TotalProfit;
}
Analysis:
- Computing pi/wi ratios: O(n).
- Sorting n items: O(nlogn) (using Merge Sort / Quick Sort).
- Greedy selection loop: Runs at most n times ⟹O(n).
- Total Time Complexity: O(n)+O(nlogn)+O(n)= O(nlogn).
- Space Complexity: O(1) auxiliary (if sorted in-place) or O(n) for ratios.
Problem 2B: Kruskal's Minimum Spanning Tree (MST)
Algorithm Kruskal(Graph(V, E))
{
Sort all edges E in ascending order of weight;
Create a Disjoint Set (MakeSet) for every vertex v in V;
MST = Empty;
for each edge (u, v) in sorted E do
{
if Find(u) != Find(v) then // Cycle check
{
Add edge (u, v) to MST;
Union(u, v);
}
}
return MST;
}
Analysis:
- Sorting all edges E: O(ElogE).
MakeSet for V vertices: O(V).
- Loop over E edges with
Find & Union (with Rank + Path Compression): O(E⋅α(V))≈O(E).
- Total Time Complexity: O(ElogE) (or O(ElogV) since E≤V2⟹logE≤2logV).
- Space Complexity: O(V+E) (for Disjoint Set parent/rank arrays and sorted edge list).
Problem 2C: Prim's Minimum Spanning Tree (MST)
Algorithm Prim(Graph(V, E), startVertex)
{
Initialize Key[v] = Infinity for all v; Key[startVertex] = 0;
Visited = Empty;
while Visited does not contain all vertices do
{
u = Unvisited vertex with minimum Key[u];
Add u to Visited;
for each neighbor v of u do
{
if (v not in Visited) and (Weight(u, v) < Key[v]) then
{
Key[v] = Weight(u, v);
Parent[v] = u;
}
}
}
return Parent[];
}
Analysis:
- With Adjacency Matrix + Simple Array:
- Outer
while runs V times. Finding min Key[u] takes O(V), updating neighbors takes O(V).
- Time = O(V2) (Best for dense graphs).
- With Adjacency List + Binary Min-Heap:
- V
Extract-Min operations: O(VlogV).
- E
Decrease-Key operations across all edges: O(ElogV).
- Time = O((V+E)logV)=O(ElogV) (Best for sparse graphs).
- Space Complexity: O(V) (for
Key[], Parent[], Visited).
Problem 2D: Dijkstra's Single-Source Shortest Path
Algorithm Dijkstra(Graph(V, E), source)
{
Initialize Dist[v] = Infinity for all v; Dist[source] = 0;
Visited = Empty;
while Visited does not contain all vertices do
{
u = Unvisited vertex with minimum Dist[u];
Add u to Visited;
for each neighbor v of u do
{
if (Dist[u] + Weight(u, v) < Dist[v]) then
Dist[v] = Dist[u] + Weight(u, v);
}
}
return Dist[];
}
Analysis:
- With Adjacency Matrix + Simple Array:
- Outer loop runs V times; each iteration scans V vertices for min and relaxes up to V edges.
- Time = O(V2).
- With Adjacency List + Binary Min-Heap:
- V
Extract-Min operations (O(VlogV)) + E edge relaxations (O(ElogV)).
- Time = O((V+E)logV)=O(ElogV).
- Space Complexity: O(V) (for
Dist[] and Visited).
- Limitation: Fails on graphs with negative edge weights.
3. Dynamic Programming (Module 3)
Control Abstraction (Bottom-Up)
Algorithm DynamicProgramming(Problem)
{
Create table DP[];
Initialize DP[base_cases];
for size = smallest to largest do
DP[size] = Optimal choice using previously saved DP values;
return DP[final_size];
}
Problem 3A: Matrix Chain Multiplication (MCM)
Algorithm MatrixChainOrder(p[], n)
{
for i = 1 to n do M[i][i] = 0;
for L = 2 to n do
{
for i = 1 to n - L + 1 do
{
j = i + L - 1;
M[i][j] = Infinity;
for k = i to j - 1 do
{
cost = M[i][k] + M[k+1][j] + p[i-1] * p[k] * p[j];
if cost < M[i][j] then
{
M[i][j] = cost;
S[i][j] = k;
}
}
}
}
return M[1][n];
}
Analysis:
- Number of DP states: Upper triangle of n×n table ⟹2n(n−1)=Θ(n2) entries.
- Work per entry: The innermost
k loop runs at most n−1 times ⟹O(n) per entry.
- Total Time Complexity: 3 nested loops (L,i,k) ⟹ Θ(n3).
- Space Complexity: Θ(n2) (for storing tables
M[n][n] and S[n][n]).
Problem 3B: Floyd-Warshall (All-Pairs Shortest Path)
Algorithm FloydWarshall(WeightMatrix, n)
{
D = WeightMatrix;
for k = 1 to n do
for i = 1 to n do
for j = 1 to n do
D[i][j] = min(D[i][j], D[i][k] + D[k][j]);
return D;
}
Analysis:
- Loops: Three nested loops (
k, i, j), each running from 1 to V (n=∣V∣).
- Inner operation: One addition and one comparison (O(1)).
- Total Time Complexity: V×V×V×O(1)= Θ(V3).
- Space Complexity: Θ(V2) (for the V×V distance matrix
D).
- Note: Works on negative edge weights (provided there are no negative weight cycles).
4. Backtracking (Module 3)
Control Abstraction
Algorithm Backtrack(step)
{
for each choice in PossibleChoices(step) do
{
Solution[step] = choice;
if IsValid(Solution, step) then
{
if IsCompleteSolution(step) then Print(Solution);
else Backtrack(step + 1);
}
}
}
Problem 4A: N-Queens Problem
Algorithm SolveNQueens(row, n)
{
if row > n then { Print(board); return; }
for col = 1 to n do
{
if IsSafe(row, col) then
{
board[row] = col;
SolveNQueens(row + 1, n);
}
}
}
Algorithm IsSafe(row, col)
{
for i = 1 to row - 1 do
{
if (board[i] == col) or (abs(board[i] - col) == abs(i - row)) then
return False;
}
return True;
}
Analysis:
- Without pruning (Brute force): nn board configurations.
- With Backtracking: Row 1 has n choices, Row 2 has at most n−1 valid column choices, Row 3 has ≤n−2, etc.
- Total Time Complexity: O(n!) worst-case (significantly faster in practice due to diagonal pruning).
- Space Complexity: O(n) (1D array
board[1..n] + recursion depth n).
5. Branch & Bound (Module 4)
Control Abstraction
Algorithm BranchAndBound(Root)
{
LiveList = [Root]; BestCost = Infinity;
while LiveList is not empty do
{
Current = PickNextNode(LiveList);
for each Child of Current do
{
if IsAnswer(Child) then Update BestCost & BestSolution;
else if EstimatedCost(Child) < BestCost then Add Child to LiveList;
}
}
return BestSolution;
}
Problem 5A: Travelling Salesman Problem (LC Branch & Bound)
Algorithm TSP_LC_BranchAndBound(CostMatrix, n)
{
Create Root node with reduced matrix and initial lower bound c_hat(Root);
Insert Root into MinHeap;
BestCost = Infinity;
while MinHeap is not empty do
{
Current = ExtractMin(MinHeap);
if Current.cost >= BestCost then continue;
if Current visits all n cities then
{
BestCost = Current.cost;
BestTour = Current.path;
continue;
}
for each unvisited city j from Current.city i do
{
Set Row i = Inf, Col j = Inf, Child[j][start] = Inf;
Reduce Child matrix -> reductionCost;
Child.cost = Current.cost + Current.matrix[i][j] + reductionCost;
if Child.cost < BestCost then Insert Child into MinHeap;
}
}
return BestTour, BestCost;
}
Analysis:
- Work per state-space node: Matrix reduction (row + column scan) takes O(n2) time.
- Total nodes in worst case: Up to (n−1)! permutations if no branches are pruned.
- Worst-Case Time Complexity: O(n2⋅n!) (exponential, since TSP is NP-Hard; however, Least-Cost pruning makes average practical runtime much faster).
- Space Complexity: Exponential in the worst case (storing reduced n×n matrices for live nodes in the Min-Heap).
Quick Master Summary Table
| Paradigm |
Problem Algorithm |
Time Complexity |
Space Complexity |
| Divide & Conquer |
2-Way Merge Sort |
Θ(nlogn) |
O(n) |
| Divide & Conquer |
Strassen's Matrix Mult. |
Θ(n2.81) |
O(n2) |
| Greedy |
Fractional Knapsack |
O(nlogn) |
O(1) / O(n) |
| Greedy |
Kruskal's MST |
O(ElogE) |
O(V+E) |
| Greedy |
Prim's MST |
O(V2) / O(ElogV) |
O(V) |
| Greedy |
Dijkstra's Shortest Path |
O(V2) / O(ElogV) |
O(V) |
| Dynamic Programming |
Matrix Chain Multiplication |
Θ(n3) |
Θ(n2) |
| Dynamic Programming |
Floyd-Warshall APSP |
Θ(V3) |
Θ(V2) |
| Backtracking |
N-Queens Problem |
O(n!) |
O(n) |
| Branch & Bound |
Travelling Salesman (LC B&B) |
O(n2⋅n!) (worst) |
Exponential (Heap) |