Dfs 18 Midterm
Dfs 18 Midterm
MIDTERM EXAMINATION
M.TECH(CS) I YEAR
1. (a) Given the roots of two binary trees write a recursive routine to determine if the two trees
are same. Two trees are same if they have the same structure and the corresponding
nodes contains the same keys.
(b) Given a binary min heap, describe a procedure which when given x as input outputs all
nodes whose values are less than x. Your algorithm should take O(N ) time where N is
the number of nodes which your algorithm outputs.
[3 + 7 = 10]
2. (a) Suppose we have a pointer to a node in a singly linked list that is guaranteed not to be
the last node in the list. We do not have pointers to any other nodes (except by following
links). Describe an O(1) algorithm that logically removes the value stored in such a node
from the linked list, maintaining the integrity of the linked list.
(b) You are given a priority queue with the following procedures: Insert() and ExtractMin().
Show how to implement an ordinary stack and an ordinary queue using the given priority
queue data structure.
[2 + (4 + 4) = 10]
3. (a) Show how to implement a queue with two ordinary stacks so that the amortized cost of
each ENQUEUE and DEQUEUE operations is O(1).
(b) Consider an array
PA[0, 1, . . . , k − 1] containing only zeros and ones. Thus A represents
k−1
the number x = i=0 A[i]2i . To add 1 modulo 2k to x we use the following procedure:
INCREMENT(A, k)
1. i ← 0;
2. while i < k AND A[i] = 1
3. A[i] ← 0;
4. i ← i + 1;
5. end while
6. if i < k,
7. A[i] ← 1
8. end if
1
Given a number x, define the potential Φ(x) of x as the number of ones in the binary
representation of x. Use a potential function argument to show that the amortized cost
of an increment as described above is O(1). Assume that the initial value of the counter
x is zero.
[5 + 5 = 10]
Propose an efficient data structure to store a GOOD matrix such that any two GOOD matrices
can be multiplied in O(n) time. Give the multiplication algorithm.
[10]
5. A d-ary heap is like a binary heap but with one possible exception, non leaf nodes have d
children instead of two children.
(a) Discuss an array implementation of a d-ary heap. In particular, write procedures for
finding the children and parent of a given node.
(b) What is the height of a d-ary heap of n elements in terms of n and d.
(c) Give an efficient procedure to implement Extract-Max in a d-ary max-heap. Analyze the
running time in terms of d and n.
[2 + 2 + 6 = 10]
[10]