Sunteți pe pagina 1din 2

Department of Computer Science and Engg, IIT Bombay

CS 213 (m): Data Structures and Algorithms Quiz1: 4 Feb 2010; 09:30–10:45
1 A4 sheet of handwritten notes is permitted. Weightage: 10%, Max Marks - 15

1. Devise an algorithm to find the middle node in a linked list, using only a single pass. (5 Marks)

(a) Show the pseudo-code for your algorithm.


(b) Show the execution of your algorithm on an example.
(c) Determine the time-complexity of your algorithm by counting the number of primitive op-
erations.
(d) Prove that the time-complexity of your algorithm is O(n).

2. An array A[1..n] has some numbers. We want to design a data structure that can efficiently
return the sum of sub-array A[i..j] for any i and j.
X
j
The query sum(i,j) must return the value A[k].
k=i
Consider the first method of solving the problem:

• Pre-processing: Store all the sums in a matrix of size n × n (say S[n][n]).


• Query Answering: Entry S[i][j] would contain the sum of sub-array A[i..j], so any query
can be answered in constant time. You may implement the function sum(i,j) as:

int sum(int i, int j)


return S[i][j];

Note that this method requries n2 entries to store the sums.


Consider the second method of solving the problem:

• Pre-processing: None. Simply retain the array A[1..n].


• Query Answering: Implement the function sum(i,j) as:

int sum(int i, int j)


int result=0;
for( int k=i; k<=j; k++)
result=result+A[k];
return result;

Note that this method uses only n entries, but answering the query takes about j − i operations
now instead of constant number of operations like in the first method. So the first method is
time-efficient and the second is space-efficient.
We require a method that is both space and time efficient. Design a solution in which the Pre-
processing uses only n entries for space AND the Query-Answering takes only a constant number
of operations. Show the pseudo-code for pre-processing and query-answering. (4 Marks)

3. Your friend claims that an O(nlogn) algorithm is always faster than an O(n2 ) algorithm, for a
given task. Do you agree? If yes, why? If no, why not? (2 Marks)
4. You have a pointer t pointing to a node in a circular linked list. Each node has two fields: Info
and a next pointer. You have no other information. The task is to delete the node pointed by t.
One way to do it is:

• Take a new pointer starting at t and traverse the entire circular list until you reach the node
before t. Call this pointer x.
• We can now delete node t by setting x->next to t->next.

Suggest a method to delete node t without being as inefficient as going round the entire list.
Clearly state any additional assumptions that you make. (4 Marks)

Figure 1:

S-ar putea să vă placă și