Final Exam
Final Exam
1
II. Calculate the best case running time Tb(n) (2 Point)
Loop Invariant:
Initiation:
Maintenance:
Termination: ,
2
3. For each of the graphs below in a pictorial representation, provide the list of vertices V
and edges E, perform BFS and DFS starting from node A in each graph (2.5 points per
graph).
Graph 1
V=
E=
II. BFS
A ® ® ® ® ® .
III. DFS
A ® ® ® ® ® .
Graph 2
V=
E=
3
II. BFS
A ® ® ® ® ® ® .
III. DFS
A ® ® ® ® ® ® .
V=
E=
II. BFS
A ® ® ® ® ® ® .
III. DFS
A ® ® ® ® ® ® .
4. For the directed Graph 3 in question 3. Find the strongly connected components using
DFS. First label the graph with the discovery and finish time
List the vertices and edges of the transpose graph G’
V’ =
E’ =
4
What are the connected components C1, C2, C3, ….
C1 => V1 =
E1 =
C2 => V2 =
E2 =
C3 => V3 =
E3 =
5. Guess an asymptotic bound Θ for running time T(n) = T(n/4) + n3 and use substitution
method proof your guess (5 points)
Guess:
5
6. Use master method to fill in the following table (1 point each)
Recurrence
A b f(n) log ba Case Θ
𝒏
𝑻(𝒏) = 𝟒𝑻 ( * + √𝒏
𝟐
𝒏
𝑻(𝒏) = 𝟒𝑻 ( * + 𝒏𝟑 + 𝒏
𝟒
𝒏 𝒏
𝑻(𝒏) = 𝟑𝑻 ( * + 𝟑 + 𝟏
𝟐 𝟒
𝒏
𝑻(𝒏) = 𝟑𝑻 ( * + 𝒔𝒊𝒏 𝒏
𝟐
𝒏
𝑻(𝒏) = 𝟒𝑻 ( * + 𝐧 𝐥𝐨𝐠 𝒏
𝟐
6
8. Ugly Numbers (5 Points)
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6,
8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention, 1 is included.
Given a number n, the task is to find nth Ugly number.
Example
Input: n = 7 Input: n = 15
Output: 8 Output: 24
7
9. Largest Sum Contiguous Subarray (5 Points)
Write a dynamic programming algorithm to find the sum of contiguous subarray within a
one-dimensional array of numbers which has the largest sum.
8
10. Coin Change (5 Points)
Given a value N, if we want to make change for N cents, and we have infinite supply of
each of S = {S1, S2, ..., Sm} valued coins, how many ways can we make the change? The
order of coins doesn’t matter.
For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},
{1,1,2},{2,2},{1,3}. So, output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five
solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So, the output should be 5.
Write a dynamic programming algorithm for the coin changing problem.