0% found this document useful (0 votes)
28 views17 pages

FinalExam 2009

The document is a final exam for a Data Structures and Algorithms course at the German University in Cairo, dated January 4, 2010. It includes various exercises covering topics such as best data structures for course prerequisites, properties of sorting algorithms, stack sorting, linked lists, binary search trees, tree traversals, and weight-balance factors. The exam consists of multiple exercises with specific marks assigned to each, and instructions for completion are provided.

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)
28 views17 pages

FinalExam 2009

The document is a final exam for a Data Structures and Algorithms course at the German University in Cairo, dated January 4, 2010. It includes various exercises covering topics such as best data structures for course prerequisites, properties of sorting algorithms, stack sorting, linked lists, binary search trees, tree traversals, and weight-balance factors. The exam consists of multiple exercises with specific marks assigned to each, and instructions for completion are provided.

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/ 17

Page 0

German University in Cairo January 4, 2010


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

Data Structures and Algorithms


Winter Term 2009-2010
Final Exam

Bar Code

Instructions: Read carefully before proceeding.

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


2) (Non-programmable) Calculators are allowed.
3) No books or other aids are permitted for this test.
4) 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.
5) 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.
6) When you are told that time is up, stop working on the test.

Good Luck!

Don’t write anything below ;-)


P
Exercise 1 2 3 4 5 6 7 8 9
Marks 8 6 10 8 8 8 13 10 9 80
Final Marks
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 1

Exercise 1 (4+4=8 Marks)


Best Data structures
The GUC needs to set a new curriculum for the faculty of architecture that will start accepting students
next year. There is a list of courses to be taught, and each course has a number of prerequisite courses.
You are given a list of courses with their prerequisites, where a course can be a prerequisite of only one
course and a course can have more than one prerequisite. For example:

Course Prerequisite courses


CSEN301 CSEN 201 MATH 201
CSEN201 CSEN102
MATH201 MATH101
CSEN102
MATH101

a) Give the best data structure to store the courses and their prerequisites so that an administrator
can print a list of courses in the order of the courses that will be given, such that no course is
given before all its prerequisites are given. Store the courses given in the example above in the data
structure you selected. Note: Use one of the data structures you took in class.
b) Justify your answer by describing an efficient way to print all courses in the appropriate order.

Solution:
The courses and their prerequisites are stored in a tree, where each course is represented as a node in the
tree. If a course has prerequisites, they are represented as the children of the node. The tree needs to be
traversed bottom-up, where the leaves are visited first, and a parent is visited only when all its children
are visited. This can be achieved using the post-order traversal of the tree.

CSEN301
JJ
t
ttt JJ
JJ
tt JJ
tt J$
yt
CSEN201 MATH201
66

 66
 66
 6

CSEN101 MATH101
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 2

Exercise 2 (2+2+2=6 Marks)


Properties of Sorting Algorithms
A sorting algorithm is stable if the order of the elements with the same value in the original array
is maintained in the sorted array. For example, you want to sort an array of strings according to their
length: [hello, hey, aloha]. A stable sorting algorithm will produce the output [hey, hello, aloha]
(because hello appears before aloha in the original list). A non-stable sorting algorithm can produce an
output with the order of hello and aloha changed, but a stable sorting algorithm will always maintain
the relative ordering of the elements.
Given the following sorting algorithms, decide if the algorithm is stable or non-stable and justify your
answer.

a) Bubble sort

void bubbleSort(int[] a) {
for (i=0; i<n-1; i++) {
for (j=0; j<n-1-i; j++)
if (a[j+1] < a[j]) {
tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
} } }

Solution:
Bubble sort is stable. The reason is that two elements with the same value will never be swapped,
thus the relative ordering of the elements with same value is maintained.
b) Selection sort

void selectionSort(int a[]) {


for (int i = 0; i < a.length - 1; i++ )
{
int minIndex = i; // index of min value
int min = a[minIndex]; // min value
for ( int j = i + 1; j < a.length; j++ )
{
if ( a[j] =< min )
{
minIndex = j;
min = a[minIndex];
}
}
int T = a[minIndex];
a[minIndex] = a[i];
a[i] = T;
} } }

Solution:
Selection sort is not stable. The reason is that the smallest element is swapped with the first
unsorted element, which changes the position of the unsorted elements. This may cause elements
having the same value to lose their relative order.
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 3

c) Insertion sort

void insertionSort(int a[])


{
for (int i = 1; i < a.length; i++ )
{
int value = a[i];
int j;

for ( j = i - 1; j >= 0 && a[j] > value; j-- )


{
a[j+1] = a[j];
}
a[j+1] = value;
}
}
}

Solution:
Insertion sort is stable. The reason is that if there is a sorted element i and a non-sorted element j,
and that i and j have the same value, j will not be shifted to a position that is before i but to some
position after it.
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 4

Exercise 3 (6+2+2=10 Marks)


Stack and Sorting

a) Given a stack of integers, write an external method that sorts the stack in ascending order, so that
the smallest element appears on top of the stack. You can use the methods pop, top, push, and
size. Note: The initial stack should be sorted after the execution of the method. Only stacks can
be used!

Solution:

public static void sort(ArrayStack a)


{
int n = a.size();
ArrayStack temp = new ArrayStack(n);

for(int i=n; i>1; i--)


{
int max = a.pop();
for(int j=0; j<i-1; j++)
{
int k = a.pop();
if(k>max)
{
temp.push(max);
max = k;
}
else
{
temp.push(k);
}
}
a.push(max);
while(!temp.isEmpty())
a.push(temp.pop());
}
}

b) What is the order of complexity of this algorithm in terms of the size of the stack? Justify your
answer.

Solution:
The time complexity of the algorithm is O(n2 ), where n is the size of the stack. The outer loop is
executed for n times to sort n elements, and each loop takes n times to determine the maximum
element.

c) What is the invariant of this algorithm?

Solution:
The invariant is that after i passes, the smallest i elements are put in the bottom of the other stack,
i.e. the temp.
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 5

Exercise 4 (8 Marks)
Linked Lists
Implement an internal method public DoublyLinkedList weirdDiff() inside the class DoublyLinkedList
that returns a DoublyLinkedList having at each Link an int value equal to the difference between two
numbers such that:

• The first operand is equivalent to the summation of all numbers occurring after the link in the same
position in the initial list.
• The second operand is equivalent to the summation of all numbers occurring before the link in the
same position in the initial list.

Note that the element in the same position will not contribute to the calculated value.
The original list should remain preserved. You should use reference manipulation only.

For example: Given the linked list below:

• The first Link in the resulting DoublyLinkedList will have the value (3+2+5)-(0).
• The second Link in the resulting DoublyLinkedList will have the value (2+5)-(1).
• The last Link in the resulting list will have the value (0)-(2+3+1).

The resulting list, for the above one, will look as follows:

Solution:

public DoublyLinkedList weirdDiff(){


DoublyLinkedList res = new DoublyLinkedList();
Link curr = first;
while(curr!=null){
int sumToFirst = 0;
int sumToLast = 0;
Link travToFirst = curr.previous;
Link travToLast = curr.next;
while(travToFirst!=null){
sumToFirst+=travToFirst.data;
travToFirst = travToFirst.previous;
}
while(travToLast!=null){
sumToLast+=travToLast.data;
travToLast = travToLast.next;
}
Link newLink = new Link(sumToLast-sumToFirst);
if(res.first==null)
res.first = newLink;
else
{
res.last.next = newLink;
newLink.previous = res.last;
}
res.last = newLink;
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 6

curr = curr.next;
}
return res;
}
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 7

Exercise 5 (6+2=8 Marks)


Binary Search Trees

a) Let T1 and T2 be two binary search trees such that every element of T1 is less than every element
of T2. Let x be a value such that T1 < x < T2. Write a method join(T1,x,T2) that produces a
binary search tree containing the elements of T1, x, and T2. The method should be implemented
internally in the tree class, i.e. you can access the root of the tree.

Solution:

public BTree join(BTree t1, int x, BTree t2)


{
BTree res = new BTree();
res.root = new Node(x);
res.root.left = t1.root;
res.root.right = t2.root;
return res;
}

b) What is the time complexity of the method? Justify your answer.

Solution:
The time complexity of the algorithm is O(1), because since T1 and T2 are both binary search trees,
the construction of the new binary search tree is just a matter of creating the new tree’s root and
performing two memory reference operations. The number of operations is constant independent
of the size of the trees.
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 8

Exercise 6 (6+2=8 Marks)


Binary Search Tree – Insertion and Deletion

a) Insert the following numbers into an initially empty binary search tree starting from left to right.

469 188 212 668 166 246 650 251 651 98 205 949

Draw the final binary search tree.

Solution:

iii 469 PPPPP


ii iiiii PPP
i PPP
i iiiiii PPP
tiii (
188 A 668 MM
qqq AA }} MMM
qqq AAA }} MMM
qq A }} MMM
xqqq A ~}} &
166 212A 650A 949
 }} AA AA
 }} AAA AAA
 }} AA AA
 ~}}
98 205 246A 651
AA
AA
AA
A
251

b) Starting with tree from part a), delete 469. Redraw the tree.

Solution:

251 PP
iiii PPP
i ii iiii PPP
iii i PPP
ii PPP
tiiii (
188A 668 MM
qqq A AA }} MMM
qqq AA }} MMM
qqq A }} MMM
xqq A ~}} &
166 212A 650A 949
 }} AA AA
 }} AAA AAA
 }} AA AA
 ~}}
98 205 246 651
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 9

Exercise 7 (3+10=13 Marks)


Tree – Traversals

a) Given the following tree

nn 63 PPPPP
n nnnn PPP
nnn PPP
nn PPP
vnnn P(
42 A 76 A
}} AA }} AA
} AAA } AA
}}} A }}} AA
~}} A ~}} A
14 A 51 A 70 81 ?
{{ AA AA ??
{{ AAA AAA ??
{{ AA AA ??
} {{ 
1 16 54 106

Give the sequence of elements after traversing the tree in preorder traversal.

Solution:
63, 42, 14, 1, 16, 51, 54, 76, 70, 81, 106
b) Implement the preorder traversal in a nonrecursive method. Hint: Use stacks as a data structure
to store the nodes. Assume that the stack is a dynamic data structure, i.e. do not worry about the
size of the stack.

Solution:

public String nonRecursivePreorder() {


String out = "";
Stack s = new Stack();
s.push(root);
while (!s.isEmpty()) {
Node n = s.pop();
if(n!= null)
{
out += n.data + " ";
s.push(n.right);
s.push(n.left);
}
}
return out;
}
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 10

Exercise 8 (10 Marks)


Binary Tree: Recursion
The „weight-balance factor“ of a binary tree is a measure of how well-balanced it is; that is, how evenly
its nodes are distributed between the left and right subtrees of each node.
The weight-balance factor of a binary tree is defined as follows: It is the maximum value of the absolute
value

|number of nodes in left subtree − number of nodes in right subtree|

for all nodes in the tree.


Add a recursive method to your binary tree class

int weightBalanceFactor();

that returns the weight-balance factor of a given binary tree.

Solution:

public int weightBalanceFactor() {


return weightBalanceFactor(root, -1);
}

public int weightBalanceFactor(Node n, int factor) {

if(n==null)
return factor;
else {
int right = count(n.right);
int left = count(n.left);
int diff = Math.abs(left-right);
if(diff>factor)
factor = diff;

right = weightBalanceFactor(n.right, factor);


left = weightBalanceFactor(n.left, factor);

if(left>right)
return left;
else
return right;
}
}

public int count(Node n) {


if(n==null)
return 0;
else
return 1 + count(n.left) + count(n.right);
}
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 11

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


Hash tables – Resolving Conflicts
Consider inserting the keys

15 8 22 1 12 19

into a hash table of size b = 7 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)
15 1
8 1
22 1
1 1
12 5
19 5

1. Using Linear probing:


Solution:
0
1 15
2 8
3 22
4 1
5 12
6 19

2. Using Chaining:
Solution:
0
1 15 → 8 → 22 → 1
2
3
4
5 12 → 19
6

3. Using quadratic probing:


Solution:
0 19 i+9
1 15
2 8 i+1
3 1 i+9
4
5 22 i+4
6 12 i+1
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 12

Exercise 10 Bonus Exercise (10 Marks)


Hash Tables
Consider two sets of integers stored in two unsorted arrays A and B. Neither A nor B can contain
duplicates, but they can share some values. We want to compute the symmetric difference of these two
sets: A−̇B

A−̇B = {x | (x ∈ A and x < B) or (x ∈ B and x < A)}

How can A−̇B be computed guaranteeing expected linear running time?


First explain the algorithm in English and justify the time complexity. Then implement it using the
following interface of Hash tables:

class HashTable {
private static int N = 11;
private int[] table = new int[N];

public boolean find(int key) { ... }


public void insert(int key) { ... }
}

class Test {
public static void main(String[] args) {
HashTable h = new HashTable();
h.insert(...);
h.insert(...);
boolean f = h.find(...);
}
}

Assume that the hash function is a perfect one. Thus, searching and insertion can be done in O(1).

Solution:
Hash all values from A into a hash table. For every value b of B, check if it is already in the hash table.
If not then add it to the output. Now do the dual: hash all values from B into an empty hash table, and
process elements of A printing them whenever they are not in this table. We perform expected constant
time operations for the elements of A and B, obtaining expected linear execution time.
Implementation:

public static LinkList symmetricDifference(int [] A, int [] B)


{
HashTable tableA = new HashTable();
HashTable tableB = new HashTable();
LinkList diff = new LinkList();

// hashing array A into hash tableA


for(int i=0; i<A.length; i++)
tableA.insert(A[i]);

// checking if the elements of B are already in the hash tableA


// if not then add it to the output list
for(int i=0; i<B.length; i++) {
if(!tableA.find(B[i]))
diff.insertLast(B[i]);
}

// performing the dual

// hashing array B into hash tableB


Data Structures and Algorithms, Final Exam, January 4, 2010 Page 13

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


tableB.insert(B[i]);

// checking if the elements of B are already in the hash tableA


// if not then add it to the output list
for(int i=0; i<A.length; i++) {
if(!tableB.find(A[i]))
diff.insertLast(A[i]);
}

return diff;

Notice: that in the worst case, only sequential single loops are performed, thus the algorithm is insured
to have linear running time, provided that the methods insert and find run in O(1) time.
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 14

Extra Sheet
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 15

Extra Sheet
Data Structures and Algorithms, Final Exam, January 4, 2010 Page 16

Extra Sheet

You might also like