Professional Documents
Culture Documents
: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Amrita Vishwa Vidyapeetham
Amrita School of Engineering, Coimbatore
B.Tech First Assessment Examinations – April 2022
Fourth Semester
Computer Science and Engineering
19CSE 212: Data Structures and Algorithms
answer Key
1. if you start with an array with one element and add a second element, you have to
copy the first element into another array. If you add a third element, you have to copy
the other two elements. If you add a fourth element, you have to copy the first three.
This adds up to 1+2+3...+N, which is equal to N(N+1)/2, which is in O(N2)
If you resize by doubling the array, then when you get some power of two size N, N/2
will have been copied 0 times, N/4 will have been copied once, N/8 will have been
copied twice, and so on. The sum of 0N/2 + 1N/4 + 2N/8 + 3N/16... is in O(N)
2. You could create an additional array B of size n. Initially set all elements of the array
to 0. Then loop through the input array A and increase B[A[i]] by 1 for each i. After
that you simply check the array B: loop over A and if B[A[i]]>1 then A[i] is repeated.
You solve it in O(n) time at the cost of memory which is O(n) and because your
integers are between 1 and n−5.
3. x = S.pop()
if (x < S.top()){
x = S.pop()
if (x < S.top())
x = S.pop()
}else{
S.pop()
if (x < S.top())
x = S.pop()
}
Solution: To get O(n log n), first loop for(i=0; i<n; i++) For each i, we can have one more
loop running for (j=0; j<n ; j=j*2)
c. O(log n)
Solution: Insert a condition such that the for loop terminates when i reaches log n value.
d. O(n^2)
e. O(2^n)
Solution: To get O(2^n), first loop iterates for i=0 to i=n. For each i, we can print 0 to 2^i.
This leads to complexity of O(2^n). More explanation
i=0
while i != n:
Traverse the list to reach the ith element (for or while loop)
i++
3 marks
9. Two lists can be merged in O(n) time O(n) space is required. The idea is to pair
up k lists and merge each pair in linear time. After the first cycle, K/2 lists are left
each of size 2×N. After the second cycle, K/4 lists are left each of size 4×N and so
on. Repeat the procedure until we have only one list left. - 3 marks
The time complexity of the above solution is O(n.log(k)) as the outer while loop in
function runs O(log(k)) times, and every time we are processing n elements. 2-
marks
10. Option 1, have topred at 0, topblue at n-1, and correspondingly define the push,
pop etc for the two stacks which grow towards the center. Other option is to start
from center with one stack growing left, and other growing right.
Clear adt with definition of push, pop, top, size, isempty – 3 marks