Daa Assignment s8
Daa Assignment s8
TASK 1
Q1) Consider the following C function.
int check(int n) {
int i, j, k, count = 0;
for (i = n / 2; i <= n; i++) {
for (j = 1; j + n / 2 < n; j = j * 2) {
for (k = 0; k < n / 2; k++) {
count++;
}
}
}
return count; }
Represent the time complexity of check in terms of Omega notation.
Ans) Time complexity represents the amount of time an algorithm takes to execute as a function
of input size nnn. Omega notation Ω\OmegaΩ represents the best-case lower bound.
Outer loop:
Middle loop:
Total Iterations
T(n)=(n/2)×(n/2)×(n/2)
T(n) = n3/8
Ignoring constants:
T(n)=O(n3)
Ω(n3)\Omega(n^3)Ω(n3)
Q2) In this problem you are given a set of n points in a 2D plane. The goal is to find the two
points that are closest to each other based on the Euclidean distance. The distance between two
points P1(x1,y1)and P2(x2,y2) is defined as:
You are required to implement both a brute-force approach (for simplicity) and an optimized
divide-and-conquer approach to solve the problem. Compare the time complexity of both
approaches and determine the closest pair of points for the given set of points
Input: Consider the following set of points in a 2D plane: Points: P1(2,3) P2(12,30) P3(40,50)
P4(5,1) P5(12,10) P6(3,4) P7(7,8) P8(15,20)
Ans) The closest pair problem aims to find two points in a plane with the minimum Euclidean
distance.
Steps
O(n^2)
Steps
Time Complexity
O(nlogn)
Given Points
Distance Calculation
D=root[(3-2)^2+(4-3)^2]
d=root(1+1)=root(2)
Q3)Find the City with the Smallest Number of Neighbors at a Threshold Distance.
There are n cities numbered from 0 to [Link] the array edges whrer edges[i]=[fromi, toi,
weighti ] represents a birectional edge between cities fromi and toi, and given the integer
distance Threshold. Return the city with the smallest number of cities that are reachable through
some path and whose distance is at most distance Threshold, If there are multiple such cities,
return the city with the greatest [Link] that the distance of a path connecting cities i and j
is equal to the sum of the edges' weights along that path.
Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
Ans) We are given cities and weighted edges. The goal is to find the city with the fewest
reachable neighbors within a threshold distance.
dist[i][j]=min(dist[i][j],dist[i][k]+dist[k][j])
Steps
Given Input
n=4
edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]]
threshold = 4
Reachable Cities
Ans) TSP finds the shortest route visiting all cities once and returning to start.
Algorithm Steps
Example Explanation
Start at A:
A→C→E→D→B→A
Cost Calculation
A–C = 1
C–E = 2
E–D = 3
D–B = 7
B–A = 3
Total:
1+2+3+7+3=161 + 2 + 3 + 7 + 3 = 161+2+3+7+3=16
Time Complexity
O(n^2)
subject to
and x1 , x2 , x3 >= 0
Ans)
Simplex Method
Problem
Maximize:
Z=3x1+5x2+4x3
Subject to:
2x1+3x2≤8
2x2+5x3≤10
3x1+2x2+4x3≤15
x1,x2,x3≥0
2x1+3x2+s1=8
2x2+5x3+s2=10
3x1+2x2+4x3+s3=15
Objective function:
Z−3x1−5x2−4x3=0
The largest positive value in Cj−Zj is 5, so x2 enters.
Ratio test
8/3,10/2,15/2
8/3
So s1 leaves.
x1=41/89
x2=41/50
x3=41/62
Z=3x1+5x2+4x3
Z=3(89/41)+5(50/41)+4(62/41)
Z=267/41+250/41+248/41
Z=765/41
Z=18.65
Zmax=765/41=18.65
At
X1=89/41,x2=50/41,x3=62/41
Thus the given linear programing problem is solved using the Simplex Method
TASK 2:
Q1) Consider a sorting algorithm that has a time complexity of O(n2) in the worst-case
scenario and O(nlogn) in the best-case scenario. What would be its average-case time
complexity using Theta notation? You have an algorithm that computes the factorial of a
number using a divide-and-conquer approach, resulting in a time complexity of
O(nlogn). What would be its time complexity using Theta notation?
Ans) String matching is the process of finding a pattern string within a larger text string. The
time complexity of string matching depends on the algorithm used and the nature of the input.
In the best case, the pattern is found quickly without many comparisons. Efficient algorithms
like binary search-based or optimized methods can achieve a time complexity of:
O(nlogn)
This happens when comparisons are minimized and the pattern matches early.
In the worst case, the algorithm has to compare the pattern with almost every position in the
text. For example, when the text and pattern have repeated characters, many unnecessary
comparisons occur. In such cases, the time complexity becomes:
O(n^2)
Thus, the time complexity of string matching varies based on the input:
Q2) Given a set of n points in a 2D plane, the goal is to find the convex hull of the points. The
convex hull must contain the outermost points, such that no point is inside the polygon formed
by the convex hull.
Input:
Consider the following set of points in a 2D plane: Points (x, y): P1(0,3) P2(2,2) P3(1,1)
P4(2,4) P5(3,1) P6(4,3) P7(3,5) P8(5,0) P9(0,0) P10(1,3)
You are required to implement algorithms to find the convex hull of this set of points. The
convex hull should be represented as a set of points that form the boundary of the convex
polygon.
Ans) The convex hull of a set of points is the smallest convex polygon that contains all the given
points. It is formed using only the outermost points, while the remaining points lie inside or on
the boundary of the polygon.
P1(0,3), P2(2,2), P3(1,1), P4(2,4), P5(3,1), P6(4,3), P7(3,5), P8(5,0), P9(0,0), P10(1,3)
We can use the Graham Scan Algorithm or Jarvis March Algorithm to find the convex hull.
Algorithm Steps
(0,0)→(5,0)→(4,3)→(3,5)→(0,3)→(0,0)
All other points lie inside this polygon. The time complexity of Graham Scan is:
O(nlogn)
Q3) Compute the transitive closure of a given directed graph using Warshall's algorithm
and for the same graph implement the all pairs shortest path problem using Floyd’s
Algorithm
Ans)Warshall’s algorithm is used to find the transitive closure of a directed graph. It tells
whether a path exists from one vertex to another. From the given graph, all vertices are reachable
from each other, so the transitive closure matrix is:
Floyd’s algorithm is used to find the shortest distance between every pair of vertices.
Given edges:
1→2=4
1 → 3 = 11
2→1=6
2→3=2
3→1=3
Thus, Warshall gives reachability, while Floyd gives minimum distance between every pair.
Q4) Utilize backtracking, find the optimal solution to a knapsack problem for the knapsack
instance n=4,m=10,(p1…p7)=(4,7,5,2) and (w1….w7)=(40,42,25,12).
Ans) Given:
n=4, Capacity=10
Weights:
(4,7,5,2)
Profits:
(40,42,25,12)
In 0/1 knapsack, each item can either be selected or rejected. Using backtracking, we explore all
possible combinations and choose the one that gives maximum profit without exceeding
capacity.
Possible combinations:
Item 1 + Item 2:
4+7=11
Not allowed.
Item 1 + Item 3:
4+5=9
Profit:
40+25=65
Item 2 + Item 4:
7+2=9
Profit:
42+12=54
Item 3 + Item 4:
5+2=7
Profit:
25+12=37
Q5) A factory manufactures two products A and B on three machines X, Y, and Z. Product A
requires 10 hours of machine X and 5 hours of machine Y a one our of machine Z. The
requirement of product B is 6 hours, 10 hours and 2 hours of machine X, Y and Z respectively.
The profit contribution of products A and B are Rs. 23/ per unit and Rs. 32 / per unit
respectively. In the coming planning period the available capacity of machines X, Y and Z are
2500 hours, 2000 hours and 500 hours respectively. Solve the optimal product mix for
maximizing the profit
Ans) Let:
x=number of Product A
y=number of Product B
Profit function:
Max Z=23x+32y
Machine X:
10x+6y≤2500
Machine Y:
5x+10y≤2000
Machine Z:
2y≤500
x,y≥0x
Simplifying:
y≤250
At (250,0)
Z=23(250)+32(0)=5750
At (0,200)
Z=23(0)+32(200)=6400
Intersection of:
10x+6y=2500
5x+10y=2000
Solving gives:
x=185.71, y=107.14
Profit:
Z=23(185.71)+32(107.14)
Z =7700
x=185.71 , y=107.14
Maximum Profit
Rs. 7700
Task-3
[Link] the following C function. Represent the time complexity of check in terms of
omega, theta, Big-O notation. int check (int n) {
int i, j, k, count = 0;
for (i = n / 2; i <= n; i++) {
for (j = 1; j + n / 2 < n; j = j * 2) {
for (k = 0; k < n / 2; k++) {
count++;
}
}
}
return count;
}
Ans: Loop breakdown:
• Outer loop (i): runs from n/2 to n → exactly ⌊n/2⌋ + 1 iterations ⇒ Θ(n)
• Middle loop (j): condition j + n/2 < n ⇔ j < n/2; j doubles each time (j = 1, 2, 4, ..., <
n/2) ⇒ number of iterations = ⌊log₂(n/2)⌋ + 1 ⇒ Θ(log n)
• Inner loop (k): runs n/2 times ⇒ Θ(n)
Total operations:
Θ(𝑛) × Θ(log 𝑛) × Θ(𝑛) = Θ(𝑛2 log 𝑛)
Asymptotic bounds:
• Big-O: 𝑂(𝑛2 log 𝑛)
• Omega: Ω(𝑛2 log 𝑛)
• Theta: Θ(𝑛2 log 𝑛)
2. In this problem you are given a set of n items, where each item has a weight and a value.
Your task is to find the subset of items that maximizes the total value without exceeding a
given weight capacity. This is a classic 0/1 Knapsack Problem, and you will use the
Exhaustive Search technique to solve it.
Given:
• A set of items with their corresponding weights and values.
• A knapsack with a weight capacity.
You need to:
1. List all possible subsets of items.
2. Compute the total weight and total value for each subset.
3. Find the subset that has the maximum value without exceeding the weight capacity.
Input:
Consider the following set of items:
• Item 1: Weight = 2, Value = 3
• Item 2: Weight = 3, Value = 4
• Item 3: Weight = 4, Value = 5
• Item 4: Weight = 5, Value = 6
Ans:
Given:
Item Weight Value
1 2 3
2 3 4
3 4 5
4 5 6
S0 {} 0 0
S1 {1} 2 3
S2 {2} 3 4
S3 {3} 4 5
S4 {4} 5 6
S5 {1,2} 5 7
S6 {1,3} 6 8
S7 {1,4} 7 9
S8 {2,3} 7 9
S9 {2,4} 8 10
S10 {3,4} 9 11
S11 {1,2,3} 9 12
S12 {1,2,4} 10 13
S13 {1,3,4} 11 14
Subset Items Included Total Weight Total Value
S14 {2,3,4} 12 15
S15 {1,2,3,4} 14 18
( = exceeds capacity)
Final Answer:
• Selected Items: Item 1 and Item 2
• Total Weight: 5
• Total Value: 7
Conclusion:
Using Exhaustive Search, we checked all possible subsets and found that:
Optimal solution = {1,2}, Max Value = 7
3. Compute the transitive closure of a given directed graph using Warshall's algorithm and for
the same graph implement the all pairs shortest path problem using Floyd's algorithm.
Problem: City of Blinding Lights
Given a directed weighted graph where weight indicates distance, for each query, determine
the length of the shortest path between nodes. There may be many queries, so efficiency
counts. For example, your graph consists of 5 nodes as in the following:
A few queries are from node 4 to node3 ,node 2 to node5 , and node 5 to node3
Ans:
Step 1: Identify Edges from Graph
From the diagram:
• 1→2=8
• 1→4=1
• 4→2=2
• 4→3=9
• 2→3=1
• 3→1=4
Step 2: Initial Distance Matrix (D)
(∞ = no direct edge)
0 8 ∞ 1
∞ 0 1 ∞
𝐷=[ ]
4 ∞ 0 ∞
∞ 2 9 0
Part A: Warshall’s Algorithm (Transitive Closure)
Boolean Matrix (T)
1 1 0 1
0 1 1 0
𝑇=[ ]
1 0 1 0
0 1 1 1
Final Transitive Closure (After Warshall)
1 1 1 1
1 1 1 1
𝑇∗ = [ ]
1 1 1 1
1 1 1 1
Interpretation:
All nodes are reachable from each other.
Final Answer:
Query Shortest Distance
1→34
2→46
3→27
Conclusion
• Warshall: All nodes are reachable
• Floyd: Efficient shortest path for all pairs
• Time Complexity:
𝑂(𝑛3 )
4. Use Branch and Bound to solve the Knapsack problem with the following:
- Weights: [2, 3, 4]
- Values: [3, 4, 5]
- Knapsack Capacity: 5
Show the bounding steps and how the solution is found.
Ans:
Given:
• Weights = [2, 3, 4]
• Values = [3, 4, 5]
• Capacity W = 5
Step 1: Compute Value/Weight Ratio
Item Weight Value Ratio (v/w)
1 2 3 1.5
2 3 4 1.33
Item Weight Value Ratio (v/w)
3 4 5 1.25
→ Pruned
Final Solution
• Selected Items: Item 1 and Item 2
• Total Weight: 2 + 3 = 5
• Maximum Profit: 3 + 4 = 7
Conclusion
Using Branch and Bound, non-promising branches were pruned using upper bounds,
leading efficiently to:
Optimal Solution Profit = 7
5.
Ans:
Given Graph (Capacities)
From the diagram:
Source = 1, Sink = 8
Edges with capacities:
• 1 → 2 = 10
• 1→3=5
• 1 → 4 = 15
• 2→5=9
• 2 → 6 = 15
• 3→2=4
• 3→6=8
• 3→7=6
• 4→3=4
• 4 → 7 = 30
• 5 → 8 = 10
• 6 → 5 = 15
• 6 → 8 = 10
• 7 → 6 = 15
• 7 → 8 = 10
Ans:
Given recurrence:
𝑇(𝑛) = 𝑎𝑇(𝑛/𝑏) + 𝑓(𝑛)
Where:
• 𝑎 = number of subproblems
• 𝑏 = size reduction factor
• 𝑓(𝑛) = extra work (divide + combine)
Step 1: Compute Critical Value
𝑛log𝑏 𝑎
This is compared with 𝑓(𝑛).
Step 2: Apply Master Theorem Cases
Case 1:
If
𝑓(𝑛) = 𝑂(𝑛log𝑏 𝑎−𝜖 )
Then:
𝑇(𝑛) = Θ(𝑛log𝑏 𝑎 )
Case 2:
If
𝑓(𝑛) = Θ(𝑛log𝑏 𝑎 )
Then:
𝑇(𝑛) = Θ(𝑛log𝑏 𝑎 log 𝑛)
Case 3:
If
𝑓(𝑛) = Ω(𝑛log𝑏 𝑎+𝜖 )
Then:
𝑇(𝑛) = Θ(𝑓(𝑛))
Final Inference
The time complexity depends on comparison between:
𝑓(𝑛)and𝑛log𝑏 𝑎
Θ(𝑛log𝑏 𝑎 ) if 𝑓(𝑛) is smaller
log 𝑎
𝑇(𝑛) = {Θ(𝑛 𝑏 log 𝑛) if equal
Θ(𝑓(𝑛)) if larger
Example (for clarity):
If:
𝑇(𝑛) = 2𝑇(𝑛/2) + 𝑛
• 𝑎 = 2, 𝑏 = 2
• 𝑛log2 2 = 𝑛
⇒ 𝑇(𝑛) = Θ(𝑛log 𝑛)
Conclusion:
Master Theorem provides a direct way to solve divide-and-conquer recurrences in:
𝑂(log 𝑛) time (analysis)
2. Given the array A = [12, 11, 13, 5, 6, 7] demonstrate how to sort it using the Heap Sort
algorithm. Show the steps for building the heap and sorting the array.
Ans:
Given Array:
𝐴 = [12,11,13,5,6,7]
Step 1: Build Max Heap
Convert array into a Max Heap (largest element at root).
Initial Array:
[12, 11, 13, 5, 6, 7]
Start heapify from last non-leaf node 𝑖 = 𝑛/2 − 1 = 2
Heapify at i = 2
• Element = 13, children = (none significant)
→ No change
Heapify at i = 1
• Element = 11, children = 5, 6
→ Already satisfies heap
→ No change
Heapify at i = 0
• Element = 12, children = 11, 13
→ Largest = 13 → swap
[13, 11, 12, 5, 6, 7]
Max Heap Formed:
[13, 11, 12, 5, 6, 7]
Step 2: Heap Sort (Extract Max)
Pass 1:
Swap root with last element
[7, 11, 12, 5, 6, 13]
Heapify:
[12, 11, 7, 5, 6, 13]
Pass 2:
[6, 11, 7, 5, 12, 13]
Heapify:
[11, 6, 7, 5, 12, 13]
Pass 3:
[5, 6, 7, 11, 12, 13]
Heapify:
[7, 6, 5, 11, 12, 13]
Pass 4:
[5, 6, 7, 11, 12, 13]
Heapify:
[6, 5, 7, 11, 12, 13]
Pass 5:
[5, 6, 7, 11, 12, 13]
Final Sorted Array:
[5, 6, 7, 11, 12, 13]
Conclusion
• Heap Sort builds a Max Heap, then repeatedly extracts the maximum element.
• Time Complexity:
Best = Average = Worst = 𝑂(𝑛log 𝑛)
4. Solve the following cost matrix using Branch and Bound to minimize the total cost:
[5, 8, 6]
[7, 3, 2]
[9, 6, 4]
Write the step-by-step process, including how bounds are calculated.
Ans:
Problem: Minimize Cost (3 × 3 Matrix)
5 8 6
[7 3 2]
9 6 4
Goal: Assign each row to one column with minimum total cost.
Step 1: Row Reduction
Subtract minimum of each row:
• Row1 min = 5 → [0, 3, 1]
• Row2 min = 2 → [5, 1, 0]
• Row3 min = 4 → [5, 2, 0]
0 3 1
[5 1 0]
5 2 0
Row reduction cost = 5 + 2 + 4 = 11
Step 2: Column Reduction
Column mins:
• Col1 min = 0
• Col2 min = 1
• Col3 min = 0
After reduction:
0 2 1
[5 0 0]
5 1 0
Column reduction cost = 1
Initial Lower Bound (LB)
𝐿𝐵 = 11 + 1 = 12
Step 3: Branching (State Space Tree)
We assign row by row.
Branch 1: Row1 → Col1
Remaining matrix:
0 0
[ ]
1 0
Possible assignments:
• Row2 → Col2 (3), Row3 → Col3 (4)
Total cost:
5 + 3 + 4 = 12
Branch 2: Row1 → Col2
Cost = 8
Remaining best:
• Row2 → Col3 (2), Row3 → Col1 (9)
Total:
8 + 2 + 9 = 19
Branch 3: Row1 → Col3
Cost = 6
Remaining:
• Row2 → Col2 (3), Row3 → Col1 (9)
Total:
6 + 3 + 9 = 18
Step 4: Choose Minimum
Best solution:
12
Final Assignment
Row Column Cost
1 1 5
2 2 3
3 3 4
Final Answer
• Minimum Cost = 12
Conclusion
Branch and Bound prunes higher-cost branches and finds optimal assignment efficiently.
5.
Ans:
Given Network
Edges with capacities:
• S →A=8
• S→D=3
• A→B=9
• D→B=7
• D→C=4
• B→T=2
• C→T=5
Solution
We use the Maximum Flow Method (Ford-Fulkerson Method) to calculate the maximum
amount of liquid that can flow from source S to sink T.
Step 1: Find Augmenting Path 1
Path:
𝑆→𝐴→𝐵→𝑇
Capacities:
• S →A=8
• A→B=9
• B→T=2
Minimum capacity:
min(8,9,2) = 2
So, flow through this path = 2 units
Step 2: Find Augmenting Path 2
Path:
𝑆→𝐷→𝐶→𝑇
Capacities:
• S→D=3
• D→C=4
• C→T=5
Minimum capacity:
min(3,4,5) = 3
So, flow through this path = 3 units
Step 3: Calculate Total Maximum Flow
Maximum Flow = 2 + 3
Maximum Flow = 5
Result
Maximum liquid flow from source S to sink T is 5 units
Thus, the maximum amount of liquid that can be sent from the source to the sink at an
instance is 5 units.
TASK 5
Answer:
Mathematical Definition of Big Omega (Ω):
A function f(n) is said to be Ω(g(n)) (Big Omega of g(n)) if and only if there exist positive constants c and n₀ such
that:
f(n) ≥ c · g(n) for all n ≥ n₀
In formal notation: f(n) = Ω(g(n)) iff c > 0, n₀ > 0 such that f(n) ≥ c·g(n) n ≥ n₀∃ ∀ Big
Omega provides a LOWER BOUND on the growth rate of a function.
Conclusion:
With c = 1 and n₀ = 1, we have proven that:
f(n) = 3n³ + 2n² + 1 ≥ 1 · (2n² + 3) = g(n) for all n ≥ 1
Therefore, f(n) = Ω(g(n)). ✓
This makes sense because f(n) is a cubic polynomial (degree 3) and g(n) is a quadratic polynomial (degree 2). A
cubic always dominates a quadratic for sufficiently large n, so it is clearly a lower bound of higher growth.
Task 5 — Question 2: Travelling Salesman Problem (Exhaustive Search)
Full Question:
You are required to use the Exhaustive Search method (brute-force) to find the optimal solution to the TSP for a
given set of cities and distances between them. Also analyze the time complexity of the brute-force approach.
Input: Consider a set of 4 cities labeled A, B, C, D with the following distances (in km):
From / To A B C D
A 0 10 15 20
B 10 0 35 25
C 15 35 0 30
D 20 25 30 0
Find the shortest route visiting each city exactly once and returning to the start.
Answer:
Approach: Exhaustive Search / Brute Force
Fix city A as the starting point. Find all permutations of the remaining 3 cities (B, C, D). Total
permutations = (n-1)! = (4-1)! = 3! = 6 routes All Possible Routes and Their Costs:
A→B→C→D→A 10 + 35 + 30 + 20 95
A→B→D→C→A 10 + 25 + 30 + 15 80
A→C→B→D→A 15 + 35 + 25 + 20 95
A→C→D→B→A 15 + 30 + 25 + 10 80
A→D→B→C→A 20 + 25 + 35 + 15 95
A→D→C→B→A 20 + 30 + 35 + 10 95
Optimal Solution:
Minimum cost = 80 km
Optimal routes: A→B→D→C→A OR A→C→D→B→A (both are 80 km — they are reverses of each other)
Answer:
Algorithm: Greedy Approach
The key insight is: Add the profit whenever the price rises from one day to the next. This is equivalent to buying
at every local minimum and selling at every local maximum.
Step-by-Step Solution:
Day Price Action Profit
Greedy Justification:
At each step, if prices[i+1] > prices[i], we add the difference (prices[i+1] - prices[i]) to profit. This captures ALL
upward movements.
Answer:
Problem Setup:
Set = {2, 3, 7, 8, 10}, Target = 15
We use backtracking to explore all subsets systematically.
Include 2 → {2}
Include 3 → {2,3}
Include 7 → {2,3,7} = 12 → continue
Include 8 → {2,3,7,8} = 20 > 15 → PRUNE
Exclude 8:
Include 10 → {2,3,7,10} = 22 > 15 → PRUNE
Exclude 7:
Include 8 → {2,3,8} = 13 → continue
Include 10 → {2,3,8,10} = 23 > 15 → PRUNE
Exclude 8:
Include 10 → {2,3,10} = 15 → *** SOLUTION *** ✓
Exclude 3:
Include 7 → {2,7} = 9 → continue
Include 8 → {2,7,8} = 17 > 15 → PRUNE
Exclude 8:
Include 10 → {2,7,10} = 19 > 15 → PRUNE
Exclude 7:
Include 8 → {2,8} = 10 → continue
Include 10 → {2,8,10} = 20 > 15 → PRUNE
Exclude 8:
Include 10 → {2,10} = 12 ≠ 15
Exclude 2:
Include 3 → {3}
Include 7 → {3,7} = 10 → continue
Include 8 → {3,7,8} = 18 > 15 → PRUNE
Exclude 8:
Include 10 → {3,7,10} = 20 > 15 → PRUNE
Exclude 7:
Include 8 → {3,8} = 11 → continue
Include 10 → {3,8,10} = 21 > 15 → PRUNE
Exclude 8:
Include 10 → {3,10} = 13 ≠ 15
Exclude 3:
Include 7 → {7}
Include 8 → {7,8} = 15 → *** SOLUTION *** ✓
Exclude 8:
Include 10 → {7,10} = 17 > 15 → PRUNE
Exclude 7:
Include 8 → {8}
Include 10 → {8,10} = 18 > 15 → PRUNE
Exclude 8:
Include 10 → {10} ≠ 15
All Valid Subsets (Summing to 15):
• Subset 1: {2, 3, 10} → 2 + 3 + 10 = 15 ✓
• Subset 2: {7, 8} → 7 + 8 = 15 ✓
Time Complexity: O(2^n) — explores all 2^5 = 32 subsets in worst case With pruning,
the actual number explored is significantly less.
Answer:
Understanding the Graph:
The bipartite graph connects boy i to girl i-1, girl i, and girl i+1 (path graph). We must find a PERFECT MATCHING
in this graph.
n M(n) Meaning
1 1 1 matching: (B1-G1)
n M(n) Meaning
3 3
4 5
5 8
6 13
7 21
8 34
9 55
Part (b): Exactly 6 boys marry girls NOT their own age
If 6 boys marry 'off-age' (i.e., cross-matches), that means 4 boys marry their exact age match, and 6 boys marry
one position up or down.
The cross-matches form pairs. 6 cross-matches = 3 adjacent pairs that cross-match.
This is equivalent to choosing 3 non-overlapping adjacent pairs from 10 positions, where each pair swaps.
Number of ways to choose k non-overlapping adjacent pairs from n positions = C(n-k, k)
For n=10, k=3: C(10-3, 3) = C(7, 3) = 35
Answer (b): 35 arrangements with exactly 6 boys marrying off-age
Analysis:
• The outer loop runs n times (i = 1 to n)
• The inner loop runs only ONCE each time because of the 'break' statement
• So printf("*") is executed exactly n times total Time Complexity of Function (i): O(n)
Analysis:
s is the sum of first k natural numbers after k iterations:
s = 1 + 2 + 3 + ... + k = k(k+1)/2
Loop terminates when s > n, i.e., k(k+1)/2 > n → k ≈ √(2n) → k = O(√n)
Time Complexity of Function (ii): O(√n)
Answer — Function (iii):
void function(int n) {
int count = 0;
for (int i = n/2; i <= n; i++)
for (int j = 1; j <= n; j = 2*j)
for (int k = 1; k <= n; k = k*2)
count++;
}
Analysis:
• Outer loop (i): runs from n/2 to n → runs n - n/2 + 1 = n/2 times → O(n) iterations
• Middle loop (j): j doubles each time (1, 2, 4, 8, ...) → runs O(log n) iterations
• Inner loop (k): k doubles each time (1, 2, 4, 8, ...) → runs O(log n) iterations
Total = O(n) × O(log n) × O(log n) = O(n log²n)
Time Complexity of Function (iii): O(n log²n)
Task 6 — Question 2: Merge Sort on Array A=[36,25,40,2,7,80,15]
Full Question:
Apply the Merge Sort algorithm to the array A=[36,25,40,2,7,80,15] and show how you would split and merge
the array step by step.
Answer:
Initial Array: [36, 25, 40, 2, 7, 80, 15]
Final Merge [2, 25, 36, 40] and [7, 15, 80]:
Compare 2 vs 7 → take 2
Compare 25 vs 7 → take 7
Compare 25 vs 15 → take 15
Compare 25 vs 80 → take 25
Compare 36 vs 80 → take 36
Compare 40 vs 80 → take 40
Take remaining 80
Result: [2, 7, 15, 25, 36, 40, 80]
Answer:
Items Table:
Item Weight Value
1 2 3
2 3 4
3 4 5
4 5 6
Capacity W = 8
DP Table dp[i][w] = max value using first i items with capacity w:
Item \ Cap 0 1 2 3 4 5 6 7 8
0 (none) 0 0 0 0 0 0 0 0 0
1 (w=2,v=3) 0 0 3 3 3 3 3 3 3
2 (w=3,v=4) 0 0 3 4 4 7 7 7 7
3 (w=4,v=5) 0 0 3 4 5 7 8 9 9
4 (w=5,v=6) 0 0 3 4 5 7 8 9 10
Answer:
Algorithm — Hamiltonian Cycle using Backtracking:
1. Start from vertex 0, add it to the path.
2. Try adding each adjacent vertex not already in the path.
3. If all vertices are visited and last vertex connects back to start → Hamiltonian Cycle found.
4. If no valid vertex exists, backtrack by removing last added vertex.
5. Repeat until a solution is found or all possibilities exhausted.
Backtracking Execution:
Start: path = [0]
Add 1 (0-1 exists): path = [0, 1]
Add 2 (1-2 exists): path = [0, 1, 2]
Add 3 (2-3 exists): path = [0, 1, 2, 3]
All 4 vertices visited! Check if 3→0 exists: No edge (0 in row 3 = 0).
BACKTRACK
No more options from 2. Backtrack: path = [0, 1]
Add 3 (1-3 exists): path = [0, 1, 3]
Add 2 (3-2 exists): path = [0, 1, 3, 2]
All 4 vertices visited! Check if 2→0 exists: Yes (adj[2][0]=1). ***
SUCCESS ***
Answer:
Bipartite Matching — Augmenting Path Method (Hopcroft-Karp concept):
Algorithm Steps:
6. Initially, all vertices are unmatched.
7. For each left vertex, try to find an augmenting path using BFS/DFS.
8. An augmenting path alternates between unmatched and matched edges.
9. If found, augment (flip) the matching along this path.
10. Repeat until no augmenting path exists.
Answer:
Recurrence Relation:
T(n) = 2T(n/2) + n
(2 subproblems, each of size n/2, combining cost = n)
Master Theorem:
For T(n) = aT(n/b) + f(n):
• a = number of subproblems (a ≥ 1)
• b = factor by which input size is reduced (b > 1)
• f(n) = cost of dividing and combining
Three Cases:
Case 1: If f(n) = O(n^(log_b(a) - ε)) for some ε > 0 → T(n) = Θ(n^(log_b(a)))
Case 2: If f(n) = Θ(n^(log_b(a))) → T(n) = Θ(n^(log_b(a)) · log n) Case 3: If
f(n) = Ω(n^(log_b(a) + ε)) for some ε > 0 → T(n) = Θ(f(n))
Answer:
Initial Array: [44, 33, 11, 55, 77, 90, 40, 60, 99, 22, 88] Strategy: Use
last element as pivot each time.
Pass 1: Pivot = 88
Array: [44, 33, 11, 55, 77, 90, 40, 60, 99, 22 | 88]
Partition: elements < 88 go left, elements > 88 go right
< 88: [44, 33, 11, 55, 77, 40, 60, 22]
> 88: [90, 99]
After partition: [44, 33, 11, 55, 77, 40, 60, 22, 88, 90, 99]
↑ pivot in final position
Pass 2 (Left subarray): [44, 33, 11, 55, 77, 40, 60, 22] — Pivot = 22
< 22: [11]
> 22: [44, 33, 55, 77, 40, 60]
Result: [11, 22, 44, 33, 55, 77, 40, 60]
Pass 3 (Right of 22): [44, 33, 55, 77, 40, 60] — Pivot = 60
< 60: [44, 33, 55, 40]
> 60: [77]
Result: [44, 33, 55, 40, 60, 77]
Final Sorted Array: [11, 22, 33, 40, 44, 55, 60, 77, 88, 90, 99]
Time Complexity:
• Best Case: O(n log n) — when pivot always divides array into equal halves
• Average Case: O(n log n)
• Worst Case: O(n²) — when pivot is always the smallest or largest element
Space Complexity: O(log n) average for recursion stack
1 2 12
2 1 10
3 3 20
4 2 15
Answer:
DP Table: dp[i][w] = maximum value using first i items with capacity w
Item \ Cap 0 1 2 3 4 5
0 (none) 0 0 0 0 0 0
1 0 0 12 12 12 12
(w=2,v=12)
2 0 10 12 22 22 22
(w=1,v=10)
3 0 10 12 22 30 32
(w=3,v=20)
4 0 10 15 25 30 37
(w=2,v=15)
DP Recurrence:
If w[i] ≤ w: dp[i][w] = max(dp[i-1][w], dp[i-1][w-w[i]] + v[i]) If
w[i] > w: dp[i][w] = dp[i-1][w]
Answer:
Understanding the Code:
The outer for loop runs from i=0 to n-1 (n iterations).
The inner while loop increments j (NOT i). j is NOT reset inside the for loop — it persists across iterations.
Key Observation:
Variable j starts at 0 and can only increment. It NEVER decreases. Since j can go from 0 to at most n, the while
loop in TOTAL across all iterations of the for loop can execute at most n times.
Conclusion:
Both best and worst case are O(n). Therefore: Time
Complexity = Θ(n) (Tight Bound)
Answer:
Step 1: Find the lowest point (anchor):
Lowest y-coordinate: (0,0). If tie, choose leftmost. Anchor
point P0 = (0,0)
Sorted order by angle (collinear points sorted by distance): (0,0), (5,0), (1,1), (2,2), (3,3), (4,4) Note: For
collinear points at the same angle, keep only the farthest: (0,0), (5,0), (4,4)
Verification:
All other points (1,1), (2,2), (3,3) lie on the line y=x between (0,0) and (4,4) — they are INSIDE or ON the hull,
which is correct.
Time Complexity: O(n log n) due to initial sorting
Task 8 — Question 3: Minimum Spanning Tree using Kruskal's Algorithm
Full Question:
Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's Algorithm (MST: Really Special
Subtree).
Graph: Multiple vertices connected by weighted edges (as shown in the figure with vertices 0-8 and various
weights).
Answer:
Kruskal's Algorithm Steps:
11. Sort all edges by weight in ascending order.
12. Initialize a Union-Find (Disjoint Set) for all vertices.
13. For each edge (in sorted order): if the two vertices are in different components, add the edge to MST
and union the components.
14. Stop when MST has (V-1) edges.
Answer:
Problem Description:
A rat starts at (0,0) in an N×N maze and must reach (N-1,N-1). The rat can only move Right or Down. A cell with 1
is open, 0 is blocked.
Algorithm:
Function solveMaze(maze, x, y, solution):
IF (x, y) == (N-1, N-1) AND maze[x][y] == 1:
solution[x][y] = 1
PRINT solution
RETURN True
IF isSafe(maze, x, y):
solution[x][y] = 1 // Mark cell
IF solveMaze(maze, x+1, y, solution): RETURN True // Move DOWN
IF solveMaze(maze, x, y+1, solution): RETURN True // Move RIGHT
solution[x][y] = 0 // BACKTRACK — unmark cell
RETURN False
RETURN False
Execution Trace:
(0,0) → Mark. Try Down:
(1,0) → Mark. Try Down:
(2,0) = 0. BLOCKED. Backtrack
Try Right:
(1,1) → Mark. Try Down:
(2,1) → Mark. Try Down:
(3,1) → Mark. Try Down: out of bounds
Try Right:
(3,2) → Mark. Try Down: out of bounds
Try Right:
(3,3) = DESTINATION! SOLUTION FOUND ✓
Answer:
Step 1: Convert to Standard Form (add slack variables s₁, s₂):
Maximize Z = 6x₁ + 8x₂ + 0s₁ + 0s₂
5x₁ + 10x₂ + s₁ = 60 4x₁ +
4x₂ + s₂ = 40
s₁ 5 10 1 0 60 60/10=
6
←min
s₂ 4 4 0 1 40 40/4=1
0
Z -6 -8 0 0 0
s₂ 2 0 -0.4 1 16 16/2=8
←min
Z -2 0 0.8 0 48
x₂ 0 1 0.2 -0.25 2
x₁ 1 0 -0.2 0.5 8
Z 0 0 0.4 1 64
Optimal Solution:
• x₁ = 8
• x₂ = 2
• Maximum Z = 6(8) + 8(2) = 48 + 16 = 64
TASK 9
Answer:
Rules of Tower of Hanoi:
15. Only one disk can be moved at a time.
16. Each move consists of taking the topmost disk from one peg and placing it on another peg.
17. No disk may be placed on top of a smaller disk.
Recursive Algorithm:
HANOI(n, source=A, destination=C, auxiliary=B):
IF n == 1:
MOVE disk 1 from A to C
RETURN
HANOI(n-1, A, B, C) // Move n-1 disks from A to B
MOVE disk n from A to C // Move largest disk
HANOI(n-1, B, C, A) // Move n-1 disks from B to C
2 3 3 seconds
3 7 7 seconds
Answer:
Array: [10, 80, 30, 90, 40, 50, 70] Pivot = 40 (at index 4)
j=0: arr[0]=10 ≤ 40 → i=0, swap arr[0] and arr[0] → [10, 80, 30, 90, 70, 50, 40]
j=1: arr[1]=80 > 40 → no swap
j=2: arr[2]=30 ≤ 40 → i=1, swap arr[1] and arr[2] → [10, 30, 80, 90, 70, 50, 40]
j=3: arr[3]=90 > 40 → no swap j=4: arr[4]=70 > 40 → no swap j=5: arr[5]=50
> 40 → no swap Place pivot at i+1=2: swap arr[2] and arr[6] → [10, 30, 40,
90, 70, 50, 80]
Result:
• Left subarray (all < 40): [10, 30]
• Pivot: [40]
• Right subarray (all > 40): [90, 70, 50, 80]
Time Efficiency Analysis:
• Partitioning step: O(n) — scans entire array once
• Quicksort average case: O(n log n)
• Quicksort worst case: O(n²) — occurs when pivot is always min/max
• Quicksort best case: O(n log n) — when pivot always splits evenly
Answer:
Dijkstra's Algorithm:
18. Initialize dist[source] = 0, all others = ∞
19. Create a priority queue with all vertices.
20. Extract vertex u with minimum distance.
21. For each neighbor v of u: if dist[u] + w(u,v) < dist[v], update dist[v].
22. Repeat until all vertices processed.
Example with representative weighted graph (from figure: A-C=3, C-B=2, A-D=4, D-E=2, C-E=5, B-F=2, E-G=5, G-
F=5):
Init - 0 ∞ ∞ ∞ ∞ ∞ ∞
1 A 0 ∞ 3 4 ∞ ∞ ∞
2 C 0 5 3 4 8 ∞ ∞
3 D 0 5 3 4 6 ∞ ∞
4 B 0 5 3 4 6 7 ∞
5 E 0 5 3 4 6 7 11
6 F 0 5 3 4 6 7 11
7 G 0 5 3 4 6 7 11
Time Complexity:
• With simple array: O(V²)
• With binary heap: O((V+E) log V)
• With Fibonacci heap: O(E + V log V)
Answer:
Problem: Place 4 queens on a 4×4 chessboard such that no two queens attack each other (no two in same row,
column, or diagonal).
Algorithm:
SOLVE_N_QUEENS(row, n, board):
IF row == n: PRINT solution; RETURN
FOR col = 0 to n-1:
IF isSafe(board, row, col):
board[row] = col // Place queen
SOLVE_N_QUEENS(row+1, n, board)
board[row] = -1 // BACKTRACK
Answer:
Definition Recap:
• NP: A problem is in NP if a given solution can be VERIFIED in polynomial time.
• NP-Hard: A problem H is NP-Hard if every problem in NP can be reduced to H in polynomial time.
• NP-Complete: A problem is NP-Complete if it is both NP and NP-Hard.
Proof of Correctness:
(→) If G has a Hamiltonian Cycle: The cycle uses only edges in E, all with weight 0. So the TSP tour cost = 0 ≤ 0. ✓
(←) If G' has a TSP tour of cost ≤ 0: Since weights are 0 or 1, the tour must use only edges with weight
0, which are exactly the edges in E. So the tour is a Hamiltonian Cycle in G. ✓
Conclusion:
Since Hamiltonian Cycle (NP-Complete) ≤_p TSP (reduces to TSP in polynomial time), and TSP ∈ NP, we conclude:
HAMILTONIAN CYCLE ≤_p TSP
Since Hamiltonian Cycle is NP-Hard, and it reduces to TSP, TSP is also NP-Hard. Therefore, TSP is NP-
Complete (NP ∩ NP-Hard). ■
Note: The optimization version of TSP (finding the actual shortest tour) is NP-Hard but not in NP (since solutions
cannot be easily verified). Only the decision version (is there a tour of cost ≤ B?) is NPComplete.