Data Structures and Algorithms - Set 11
Data Structures and Algorithms - Set 11
1. Consider a hash table of size seven, with starting index zero, and a hash function (3x +
4)mod7. Assuming the hash table is initially empty, which of the following is the contents of
the table when the sequence 1, 3, 8, 10 is inserted into the table using closed hashing? Note
that _ denotes an empty location in the table.
(A) 8, _, _, _, _, _, 10
(B) 1, 8, 10, _, _, _, 3
(C) 1, _, _, _, _, _,3
(D) 1, 10, 8, _, _, _, 3
Answer (B)
Please see http://lcm.csa.iisc.ernet.in/dsa/node38.html for closed hashing and probing.
- - - - - - -
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 1 is 0, so let us put the value at 0
1 - - - - - -
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 3 is 6, so let us put the value at 6
1 - - - - - 3
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 8 is 0, but 0 is already occupied, let us put the value(8)
at next available space(1)
1 8 - - - - 3
0 1 2 3 4 5 6
The value of function (3x + 4)mod 7 for 10 is 6, but 6 is already occupied, let us put the
value(10) at next available space(2)
1 8 10 - - - 3
0 1 2 3 4 5 6
2. In an unweighted, undirected connected graph, the shortest path from a node S to every
other node is computed most efficiently, in terms of time complexity by
(A) Dijkstras algorithm starting from S.
(B) Warshalls algorithm
(C) Performing a DFS starting from S.
(D) Performing a BFS starting from S.
Answer(D)
3. A complete n-ary tree is a tree in which each node has n children or no children. Let I be
the number of internal nodes and L be the number of leaves in a complete n-ary tree. If L =
41, and I = 10, what is the value of n?
(A) 3
(B) 4
(C) 5
(D) 6
Answer (C)
For an n-ary tree where each node has n children or no children, following relation holds
L = (n-1)*I + 1
Where L is the number of leaf nodes and I is the number of internal nodes.
L = 41 , I = 10
41 = 10*(n-1) + 1
(n-1) = 4
n = 5
int gcd(n,m)
{
if (n%m ==0) return m;
n = n%m;
return gcd(m,n);
}
Answer (A)
Above code is implementation of the Euclidean algorithm for finding Greatest Common Divisor
(GCD).
Please see http://mathworld.wolfram.com/EuclideanAlgorithm.html for time complexity.
(A) (n)
(B) (nlogn)
(C) (logn)
(D) (loglogn)
Answer (D)
Recursive relation for the DoSomething() is
We have ignored the floor() part as it doesnt matter here if its a floor or ceiling.