0% found this document useful (0 votes)
5 views4 pages

Algorithms and Complexity Assignment Solutions

The document is an assignment on algorithms and complexity, consisting of 25 problems that cover various topics such as recurrence relations, asymptotic notations, sorting algorithms (merge sort and quick sort), graph algorithms (Kruskal's and Prim's), shortest path algorithms, and dynamic programming. Each problem requires the application of theoretical concepts and practical implementations to solve algorithmic challenges. The assignment also includes tasks related to time complexity analysis and optimization techniques.

Uploaded by

p25cs001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Algorithms and Complexity Assignment Solutions

The document is an assignment on algorithms and complexity, consisting of 25 problems that cover various topics such as recurrence relations, asymptotic notations, sorting algorithms (merge sort and quick sort), graph algorithms (Kruskal's and Prim's), shortest path algorithms, and dynamic programming. Each problem requires the application of theoretical concepts and practical implementations to solve algorithmic challenges. The assignment also includes tasks related to time complexity analysis and optimization techniques.

Uploaded by

p25cs001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ALGORITHMS AND COMPLEXITY

Assignment

1. Solve the following recurrence relation and find the time complexity.
i. T(n)=7T(n/2)+18n2,
ii. T(n)=2T(n/2)+nlogn
2. Apply suitable asymptotic notations to compute the upper bound and lower bound time
complexity of f(n).
i. f(n)= 2n3 + 6n2 + 5n + 7.
ii. f(n) = 2n + 3n3 +n2+5n
3. Solve the following recurrences relation using suitable method

T(n)=7T(n/2)+n2
T(n)=2T(n/2)+sqrt(n)
4. Apply suitable asymptotic notation to compute the time complexity of the following
functions.
(i). Show that for any real constant a and b, where b>0, (n+a)b = ϴ(nb)
(ii). Is n!= o(nn)
(iii) 2n+1 = O(2n)
5. Solve the following recurrences relation using suitable method.
i. T(n)= T(root(n)) + n (using Recursion tree method)
ii. T(n) = 4T(n/2) +n2 * logn

6. Solve the recurrence relation using master method for T(n) = 7T (n/2) + n and find the time
complexity.

7. Apply merge sort algorithm to sort the list {N,A,R,C,I,S,S,I,S,T,I,C } in alphabetical order.
Show all the steps in sorting. Find the recurrences function and calculate the worst-case
analysis of this algorithm.

8. Write quick sort algorithm and apply to sort the list {U,N,I,V,E,R,S,I,T,Y} in alphabetical
order. Show all the steps in sorting. Also calculate the worst-case analysis of this algorithm
through its recurrences function.

9. Find the minimum spanning tree of the following Graph using Kruskal Algorithm and Prim’s
algorithm; Find the time complexity of the both algorithms.

10. Explain single source all pair shortest path algorithm; write the pseudocode of the algorithm
and find the shortest path of a given Graph, considering ‘v1’ is the starting node of the graph
.
ALGORITHMS AND COMPLEXITY
Assignment

11. Find and construct the optimal binary search tree from the followings.
Nodes: A, B, C, D
Search Probability 0.1, 0.2, 0.4, 0.3
12. Let M1, M2, M3, and M4 be four matrices of dimensions 5,6,7,8,9 respectively. Calculate the
minimum number of scalar multiplications required to find the product of M1xM2x M3xM4
and find the order of multiplication using dynamic programming.
13. Sales agent daily required visit all the locations {A,B,C,D} in such a manner that he has to
cover all the locations in the respective area with minimum travel cost. Compute the
minimum travel cost using brute force method.

14. In a shop, there are N items where each item has some weight and profit associated with it
and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. As
customer, you collect the items into the bag such that the sum of profits associated with them
is the maximum possible. Solve the following using brute force method. N = 3, W = 5,
profit[] = {1, 2, 3}, weight[] = {4, 5, 1}
15. Given the following array [ 28, 41, 42, 94, 56, 28, 56, 47, 61, 14, 72, 80] and assume that
quick sort will be used to sort this array in increasing order. Select the pivot value as last
element. Calculate the worst-case complexity through recurrences relation. Also, explain why
this makes quick sort perform efficiently as compare to megre sort algorithm.
16. Zomato agent daily drops the required foods to the address assigned in such a manner that he
has to cover all the houses in the respective area with minimum travel cost. Compute the
minimum travel cost using brute force method.
ALGORITHMS AND COMPLEXITY
Assignment

17. In a shop, all the items are arranged with its index in increasing order. The owner of that shop
searching one item, but that item is not present in that shop. Apply best searching algorithm
and find out the worst-case analysis of that searching algorithm through recurrences function?
18. Define recurrence equation. Find the recurrence relation of the following function and
calculate the time complexity.
public static int Recursion(int n) {
if (n <= 1) {
return 1; }
int sum = 0;
for (int i = 0; i < n; i++) {
sum += Recursion(i)+ Recursion(i-1);
}
return sum;
}
19. Solve the following using substitution method and verify using master method.
i). T(n)=2T(n/2)+n/log n with base case T(1)=1
ii) T(n)=T(2n/3)+T(3n/2)+cn , where c>0 is a constant and T(1)=O(1).
20. Implement a modified Quick Sort to sort a distinct array of n elements in increasing order.
that always selects the pivot as the third smallest element in the current subarray.
i. Construct the worst-case input array for this version of Quick Sort and explain how the
partitioning behaves on that input.
ii. Find the worst-case time complexity of the modified quick sort based on your above input.
21. Implement a modified Binary Search algorithm on array of n strings that performs the
following.

Exact Match: it should search first look for an exact match of a target string in the array. If
an exact match is found, return that string and its index position immediately.

Closest Lexicographical Match: If an exact match is not found, return the closest match
based on lexicographical order and its half of the length should be the same or more length of
the smallest string in the given array.
Array={“Agra”, “Amaravati”, “Chennai”, “Delhi”, “Guntur”, “Hyderabad”, “Indore”,
“Patna”, }
Key=”Guntur”, Output= Guntur, index = 3 [Exact match found]
Key=”Amaresh”, Output=“Amaravati”, index=2 [Closest Lexicographical Match]
ALGORITHMS AND COMPLEXITY
Assignment

22. Write the modified Binary search algorithm and analyse the time complexity of the algorithm
Apply the dynamic programming approach to find an optimal order for multiplying 4
matrices with dimensions 5, 6, 4, 6, 3.
I. Write a dynamic programming algorithm to solve this problem and determine the
minimum number of scalar multiplications required.
II. Derive the recurrence relation i.e T(n) for finding the number of ways of representing
n matrices.
III. Print the order of multiplication with minimum number of scalar [Link]
23. Apply Dijkstra’s algorithm to find the shortest path from v1 to all other vertices and show the
step-wise implementation of Dijkstra’s algorithm over the given graph.

24. Find maximum flow from node ‘s’ to node ‘t’ in the following network using Ford-Fulkerson
algorithm (Derive the reduced graph and augmented path for each step)

25. Design an efficient algorithm to determine whether there exists a subset S′⊆S such that the
sum of elements in S′ is exactly T and discuss the time complexity of the algorithm, where S
is the given set of integers, S′ is subset sum and T is the target integer. Given a n distinct
positive integers, find all combinations of these numbers whose sum=M.
S={5,10,12,13,15,18}
M=30, N=6

Common questions

Powered by AI

The dynamic programming approach involves building a table to store sub-problem solutions. The primary idea is to find the optimal place to parenthesize the product to minimize the number of scalar multiplications. The process starts by filling in the cost of multiplying two adjacent matrices, then extends to sets of three matrices, continuing until it covers the entire chain. The key insight is splitting matrices [Ai...Aj] at every possible k and computing the cost of each configuration: cost = m[i][k] + m[k+1][j] + dimensions[i-1]*dimensions[k]*dimensions[j]. It utilizes overlapping subproblems and optimal substructure properties for computation. The minimal value represents the final solution. The approach requires O(n^3) time and O(n^2) space .

Prim's Algorithm builds the MST by growing one edge from an existing tree incrementally, focused on adjacent expansions, often utilizing a priority queue to select the minimum weight edge, leading to a time complexity of O(V^2) or O(E + log V) with Fibonacci heaps. Kruskal's Algorithm begins with the smallest edge and works outwards, adding edges as long as they don't form a cycle. It's more efficient on sparse graphs given its edge-based sorting, and its time complexity is O(E log V). Prim's is inherently greedy within a node-focused scope, contrasting Kruskal's edge-driven emphasis .

Merge Sort has a guaranteed time complexity of O(n log n) as it consistently splits the array in half and merges them back in linear time, whereas Quick Sort's efficiency largely depends on the choice of the pivot. Quick Sort is faster in practice due to better cache performance as it operates in-place and does not require additional memory for merges like Merge Sort. Quick Sort outperforms Merge Sort primarily when the pivot choice prevents skewed partitions, maintaining closer to O(n log n) complexity. If carefully implemented, especially by randomizing pivots or using median-of-three selections, it can perform exceedingly well even on average cases .

Dijkstra's Algorithm fails to find the shortest path in graphs with negative weight edges, as it assumes that once a vertex is processed and its shortest path determined, it need not be reconsidered. In the presence of negative edges, paths may change even after finalization, invalidating calculations. This limitation can be addressed by using the Bellman-Ford algorithm, which can handle negative weights and detect negative cycles, albeit with a higher time complexity of O(VE), where V is the number of vertices and E is the number of edges .

The Ford-Fulkerson method works by repeatedly finding augmenting paths from the source to the sink in a flow network, increasing the flow along these paths until no more augmenting paths can be found. The method's maximal flow depends on selecting augmenting paths using Breadth-First Search (BFS), ensuring efficient updates to path flows without cycles diminishing progress. Infinite loops can arise with irrational numbers, necessitating the choice of integral capacities where applicable. Proper tracking of remaining capacities prevents edge oversaturation. Its time complexity is dictated by O(E*f) steps, where E is the number of edges and f is the maximum flow .

Kruskal's Algorithm involves sorting all the edges of the graph by weight in non-decreasing order. It then iteratively adds edges to the Minimum Spanning Tree (MST) without forming a cycle until (n-1) edges are added, where n is the number of vertices. The critical factors affecting its time complexity are the edge-sorting step, typically O(E log E), where E is the number of edges, and the operations needed to check and manage cycles during the edge-adding process, generally handled by a Disjoint Set Union (DSU) structure .

The substitution method involves guessing a solution and proving it by induction. For T(n)=2T(n/2)+n/log n, assume T(n) = O(n) substantiates a simplistic check. Let's propose T(n) ≤ cn for some constant c, and verify by substitution: T(n) = 2T(n/2) + n/log n ≤ 2(cn/2) + n/log n = cn + n/log n. Because 1/log n decreases towards zero for large n, cn dominates, maintaining T(n) ≤ O(n). Verification using induction complements Master Theorem's spurious compliance, suggesting T(n) = O(n log n), yet attenuation implies T(n) ≤ cn for practical boundary preservation .

To solve T(n) = T(√n) + n via the recursion tree, decompose the problem in several levels. At level i, the input size becomes (√n)^(1/2^i) down to T(1). The depth of the recursion tree can be found by solving n^(1/2^d) = 1; hence, d = log(log(n)). The cost at each level is n, leading to total work represented by a geometric series with d terms, each costing n. Thus, the complexity is O(n log log n), as every division into smaller problems multiplies the temporal complexity by that logarithmic depth without varying .

The Master Theorem can be applied to T(n) = 7T(n/2) + n by matching it to the form T(n) = aT(n/b) + f(n), where a = 7, b = 2, and f(n) = n. Here, f(n) = n is O(n^log_b(a)) because n is O(n^log_2(7)), which makes them asymptotically equal. According to the Master Theorem, if f(n) is Θ(n^c) for c < log_b(a), then T(n) is Θ(n^log_b(a)). Since c = 1 and log_2(7) > 1, T(n) is Θ(n^log_2(7)), indicating a time complexity of O(n^log_2(7)).

Improvements for quick sort regarding pivot selection focus on minimizing the chances of worst-case performance by avoiding consistently poor pivot choices like the smallest or largest element. Selecting the median of three elements (first, middle, last), using randomization, or employing a median-of-medians approach reduces the likelihood of skewed partitions. This practice enhances the average-case performance by balancing subarrays more effectively, maintaining closer to O(n log n) in the average case, compared to the potential O(n^2) with poor pivot choices. Such strategies align the theoretical assurances with practical efficiency gains .

You might also like