0% found this document useful (0 votes)
13 views13 pages

FinalExam 2011

This document is the final exam for the Data Structures and Algorithms course at the German University in Cairo, dated January 19, 2012. It contains various exercises related to algorithms, data structures, binary search trees, hash tables, and heaps, along with specific programming tasks and solutions. The exam is structured with instructions, marks allocation, and requires students to demonstrate their understanding of the subject matter through coding and theoretical explanations.

Uploaded by

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

FinalExam 2011

This document is the final exam for the Data Structures and Algorithms course at the German University in Cairo, dated January 19, 2012. It contains various exercises related to algorithms, data structures, binary search trees, hash tables, and heaps, along with specific programming tasks and solutions. The exam is structured with instructions, marks allocation, and requires students to demonstrate their understanding of the subject matter through coding and theoretical explanations.

Uploaded by

Zagg Jass
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Page 0

German University in Cairo January 19, 2012


Faculty of Media Engineering and Technology
Prof. Dr. Slim Abdennadher

Data Structures and Algorithms


Winter term 2011-2012
Final Exam

Bar Code

Instructions: Read carefully before proceeding.

1) Please tick your major

Major
IET/MET
Mechatronics
BI

2) Duration of the exam: 3 hours (180 minutes).

3) (Non-programmable) Calculators are allowed.


4) No books or other aids are permitted for this test.

5) This exam booklet contains 15 pages, including this one. Three extra sheets of scratch paper are
attached and have to be kept attached. Note that if one or more pages are missing, you will lose
their points. Thus, you must check that your exam booklet is complete.

6) Write your solutions in the space provided. If you need more space, write on the back of the sheet
containing the problem or on the three extra sheets and make an arrow indicating that. Scratch
sheets will not be graded unless an arrow on the problem page indicates that the solution
extends to the scratch sheets.

7) When you are told that time is up, stop working on the test.

Good Luck!

Don’t write anything below ;-)



Exercise 1 2 3 4 5 6 7 8
Marks 6 10 8 10 9 10 21 6 80
Final Marks
Data Structures and Algorithms, Final Exam, January 19, 2012 Page 1

Exercise 1 (6 Marks)
Implement a method that takes two input arguments: a sorted array of integers arr and an integer v. It
returns a boolean value true if v is contained in arr and false otherwise. Your implementation should
have a runtime of O(log n), where n is the length of arr. Explain why your method has this runtime.

Solution:

public static boolean arrayContains(int[] arr, int v) {


int min = 0;
int max = arr.length - 1;
int mid = max + min / 2;
while (max >= min) {
if (arr[mid] == v) {
return true;
}
else if (arr[mid] < v) {
min = mid;
mid = (min + max) / 2;
}
else {
max = mid;
mid = (min + max) / 2;
}
}
return false;
}

Runtime justification: This method just implements binary search. It has a runtime of O(log n) because
we are halving the size of our search space with each iteration of the loop. We can only halve the space
log n times. The rest of the operations are all O(1), so we are looking at O(log n).
Data Structures and Algorithms, Final Exam, January 19, 2012 Page 2

Exercise 2 (4+6=10 Marks)


Consider the given definitions of a node Node and a singly linked list SList. Add two methods to SList.

public class Node {


public int key;
public Node next;
}

public class SList {


private Node head;
}

a) Write a method isSortedAsc for the class SList which returns true if the list is sorted in an
ascending (non-decreasing) order or the list is empty. Otherwise, return false.
Solution:

public boolean isSortedAsc() {


if (head == null)
return true;
SNode node = head;
while (node.next != null) {
if (node.key > node.next.key)
return false;
else
node = node.next;
}
return true;
}

b) Write a method putInPlace for the class SList that accepts an integer x. The method should first
check whether the list is sorted in a non-decreasing order. If it is sorted, the method should insert x
into the correct position so the list remains sorted. Otherwise, it will not modify the list and return
false.
You can make use of the method isSortedAsc from part a).
Solution:

public boolean putInPlace(int x) {


if (isSortedAsc() == false)
return false;
SNode newNode = new SNode();
newNode.key = x;
if (head == null) {
head = newNode;
return true;
}
if (head.key >= newNode) {
newNode.next = head.next;
head = newNode;
return true;
}
SNode target = head;
while (target.next != null && target.next.key < x)
target = target.next;
newNode.next = target.next;
target.next = newNode;
return true;
}
Data Structures and Algorithms, Final Exam, January 19, 2012 Page 3

Exercise 3 (2+2+2+2=8 Marks)

a) Draw the binary search tree that results from inserting the values 1 to 7 in each of the following
orders (reading from left to right):

• 5 3 7 6 2 1 4
• 1 2 3 4 5 6 7
• 4 3 5 2 6 1 7

Solution:
The binary search tree that results from inserting the values 5 3 7 6 2 1 4 in that order is:

5H
vv HHHH
vvv HH
v HH
vvv HH
zvv $
35 7
55
55
 5 
2 4 6


1

The binary search tree that results from inserting the values 1 2 3 4 5 6 7 in that order is:

15
55
55
5
25
55
55
5
35
55
55
5
45
55
55
5
55
55
55
5
65
55
55
5
7

The binary search tree that results from inserting the values 4 3 5 2 6 1 7 in that order is:

41
11
11
 1
3 51
11
11
 1
2 61
11
11
 1
1 7
Data Structures and Algorithms, Final Exam, January 19, 2012 Page 4

b) If a specific type of traversal is performed on the three trees above, then the same sequence will be
obtained. Determine the sequence as well as the type of traversal.

Solution:
The Inorder traversal of a binary search tree will return the values in the tree sorted in ascending
order. Thus, the Inorder traversal of the previous trees will return the sequence 1 2 3 4 5 6 7.
Data Structures and Algorithms, Final Exam, January 19, 2012 Page 5

Exercise 4 (2+8=10 Marks)


Given a standard binary search tree where each key is greater than the keys in its left subtree and smaller
than the keys in its right subtree, a reverse binary search tree is a tree where each key is smaller than the
keys in its left subtree and greater than the keys in its right subtree.

a) What is the reverse binary search tree of the following binary search tree:

n 50 PPPP
nnnnn PPP
nnn PPP
nnn PPP
vnnn PP(
30 A 90 ?
}}} AAA }}} ???
} AA } ??
}} AA }} ?
~}
} ~}}
20 40 80 A 120=
}}} AAA ==
==
}} AA
} AA ==
~}} 
60 85 140

Solution:

p 50 NNNN
pp ppp NNN
p pp NNN
p NNN
wppp '
90 = 30 =
~~ ===  ==
~~ =  ==
~ ==  ==
~ ~   
120 80 = 40 20
}}}  ===
} ==
}}  =
~}} 
140 85 60

b) Implement a linear-time algorithm that given a binary search tree it transforms it into a reverse
binary search tree.

Solution:

public static void mirror(BTree t)


{
mirror(t.root);
}
public static void mirror(Node current)
{
if (current != null)
{
// sub-trees
mirror(current.left);
mirror(current.right);
// swap the left & right children
Node temp = current.left;
current.left = current.right;
current.right = temp;
}
}
Data Structures and Algorithms, Final Exam, January 19, 2012 Page 6

Exercise 5 (3+3+3=9 Marks)


Consider inserting the keys

27 40 30 56 53 118 121 131 134

into a hash table of size b = 13 and using the hash function h(x) = x%b.

a) Show where the numbers below end up in the hash table if we insert them in the order (left to
right).

Solution:
After applying the hash function:

x h(x)
27 1
40 1
30 4
56 4
53 1
118 1
121 4
131 1
134 4

1. Using Linear probing:


Solution:
0
1 27
2 40
3 53
4 30
5 56
6 118
7 121
8 131
9 134
10
11
12

2. Using quadratic probing:


Solution:
Data Structures and Algorithms, Final Exam, January 19, 2012 Page 7

0 118
1 27
2 40
3
4 30
5 56
6
7 134
8 121
9
10 53
11 131
12

3. Using Chaining:
Solution:
0
1 27 → 40 → 53 → 118 → 131
2
3
4 30 → 56 → 121 → 134
5
6
7
8
9
10
11
12
Data Structures and Algorithms, Final Exam, January 19, 2012 Page 8

Exercise 6 (5+5+5(Bonus)=10 Marks)


Given two arrays a[] and b[], each containing n distinct numbers, design two algorithms (with the
performance requirements specified below) to determine whether the two arrays contains precisely the
same set of numbers (but possibly in a different order).
Your answer will be graded on correctness, efficiency, and clarity.

a) Design an algorithm for the problem whose running time is polynomial; O(n2 ). Give a concise
English description of your algorithm.

Solution:

1. Traverse array a element by element and for each element, compare it with all the elements
in array b.
2. If the an element in a was not found in b then, then return false.
3. If all the elements in a where found in b, then return true.

Traversing the array b to compare an element from a to all its elements has the complexity of O(n).
Repeating this n times to compare all elements in a to all elements in b will have the complexity of
O(n2 ).

b) Design an algorithm for the problem whose running time is linear under reasonable assumptions.
Be sure to state any assumptions that you make. Give a concise English description of your
algorithm.

Solution:
Assume that there exists a hash table with a perfect hash function (inserting in and searching the
hash table runs in O(1)).
1. Insert all the elements in array a in a hash table.
2. Traverse the array b and for each element search for it in the hash table.
3. If an element in b was not found in the hash table, return false.
4. If all elements were found, return true.

Inserting all elements of a in the hash table will run in O(n). Traversing all the elements in b and
search for them in the hash table will also run in O(n). Thus, the total running time will be O(n).

c) Implement the algorithm of part b).

Solution:

public static boolean sameNumber(int[] a, int[] b) {

Hashtable ht = new Hashtable(a.length);

for(int i=0 ;i<a.length; i++)


ht.put(a[i]);

for(int i=0; i<b.length; i++)


if(ht.contains(b[i])==false)
return false;

return true;
}
Data Structures and Algorithms, Final Exam, January 19, 2012 Page 9

Exercise 7 (3+2+6+6+4=21 Marks)


A binary heap is a complete binary tree which satisfies the following ordering property:
The value of each node is greater than or equal to the value of its parent, with the minimum-value
element at the root.
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled,
and all nodes are as far left as possible [Wikipedia].

6
/ \
/ \
/ \
/ \
7 12
/ \ /
/ \ /
10 15 17

In a heap the highest (or lowest) priority element is always stored at the root, hence the name heap. A
heap is not a sorted structure and can be regarded as partially ordered. As you see from the picture,
there is no particular relationship among the nodes on any given level, even among the siblings.
In this exercise, you will implement a heap using arrays.
A complete binary tree can be uniquely represented by storing its level order traversal in an array.

The root is the second item in the array. We skip the index zero cell of the array for the convenience of
implementation. Consider k-th element of the array, then

• its left child is located at 2*k index

• its right child is located at 2*k+1 index


• its parent is located at k/2 index

For simplicity, implement a heap class of integers using arrays. Follow the following steps.

a) Define the attributes of your class: The array, its maximum size and the number of elements in the
heap.
Data Structures and Algorithms, Final Exam, January 19, 2012 Page 10

Solution:

public class Heap {

private int maxSize;


private int nElem;
private int[] heap;
}

b) Define a constructor that takes the size of the heap as an argument and initializes the attributes
accordingly.

Solution:

public Heap(int maxSize) {


this.maxSize = maxSize+1;
heap = new int[maxSize+1];
nElem = 0;
}

c) Define a method called insert to insert a new element into the heap. The new element is initially
appended to the end of the heap (as the last element of the array). The heap property is repaired by
comparing the added element with its parent and moving the added element up a level (swapping
positions with the parent). This process is called percolation up. The comparison is repeated until
the parent is larger than or equal to the percolating element.
Assume you would like to insert 5 into the heap above. The insert method will be executed as
follows:

Solution:

public void insert(int x) {

//Insert a new item to the end of the array


int pos = ++nElem;

//Percolate up
while(x < heap[pos/2]) {
heap[pos] = heap[pos/2];
pos = pos/2;
}

heap[pos] = x;
}
Data Structures and Algorithms, Final Exam, January 19, 2012 Page 11

d) Implement a method called deleteMin that deletes the minimum element. The minimum element
can be found at the root, which is the first element of the array. We remove the root and replace it
with the last element of the heap and then restore the heap property by percolating down.

Solution:

public int deleteMin() {


// Get he minimum
int min = heap[1];

// Set the root to the last element


heap[1] = heap[nElem];
nElem--;

//Precolate down
percolateDown(1);

return min;
}

private void percolateDown(int k) {


int tmp = heap[k];
int child;

while(2*k <= nElem) {

// Get the left child of node k


child = 2*k;

// Set the child to be the largest from left and right


if(child != nElem && heap[child] > heap[child+1])
child++;

// If the child is small smaller, swap


if(tmp > heap[child])
heap[k] = heap[child];
else
break;

k = child;
}

heap[k] = tmp;
}

e) What is the time complexity of insert and deleteMin? Justify your answer.

Solution:
inert: O(log n). Appending the element at the end of the heap takes O(1). Percolating the element
up would take, worst case, O(log n); the number of swaps required to move the element from the
last level to the root of the tree, which is equivalent to the height of the tree (the height of a complete
tree is log n).
deleteMin: O(log n). Removing the root takes O(1). Replacing the root with the last element takes
O(1). Percolating this element down would take, worst case, )O(log n); the number of swaps
required to move the element from the root to the last level of the tree, which is equivalent to the
height of the tree (the height of a complete tree is log n).
Data Structures and Algorithms, Final Exam, January 19, 2012 Page 12

Exercise 8 (3+3=6 Marks)


A priority queue is a data structure that supports storing a set of values, each of which has an associated
key. Each key-value pair is an entry in the priority queue. The basic operations on a priority queue are:

• insert(k, v): insert value v with key k into the priority queue
• removeMin(): return and remove from the priority queue the entry with the smallest key

a) Assume that you have the Heap class. How can use this class to implement a priority class? Give a
concise English description.

Solution:

• Create the priority queue with one heap.


• insert(key, value): For each key and value pair inserted in the priority queue, create a
Comparable object of the pair and insert it in the heap. The Comparable objects will use key to
compare their priorities.
• removeMin(): To remove the value with the smallest minimum, remove the minimum object
in the heap (the root of the heap) and return its value.

b) What is the advantage of using the Heap class compared to unsorted or sorted arrays? Think about
the time complexity of the methods!

Solution:
For a priority queue implemented using unsorted arrays, insert has the time complexity of O(1)
and removeMin has the time complexity of O(n).
For a priority queue implemented using sorted arrays, insert has the time complexity of O(n) and
removeMin has the time complexity of O(1).
But for a priority queue implemented using heaps, both insert and removeMin has the time
complexity of O(log n).
This gives an advantage for priority queues using heaps since it guarantees one faster operation
than the other two implementations.

You might also like