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

FinalExam 2006

The document is a final exam for a Data Structures and Algorithms course at the German University in Cairo, covering various topics such as binary search trees, linked lists, and quaternary search trees. It consists of multiple exercises with questions requiring theoretical explanations, algorithm implementations, and code analysis. The exam is structured to assess students' understanding of data structures and their applications, with a total of 100 marks available.

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

FinalExam 2006

The document is a final exam for a Data Structures and Algorithms course at the German University in Cairo, covering various topics such as binary search trees, linked lists, and quaternary search trees. It consists of multiple exercises with questions requiring theoretical explanations, algorithm implementations, and code analysis. The exam is structured to assess students' understanding of data structures and their applications, with a total of 100 marks available.

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 Winter 2006/2007


Computer Science Department
Prof. Dr. Slim Abdennadher

Data Structures and Algorithms


Winter term 2006/2007
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 10 11
Marks 6 10 10 6 10 12 10 8 8 8 12 100
Final Marks
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 1

Exercise 1 (6 Marks)

a) True or False? Justify your answer. Searching for a value x in a binary search tree is always faster
than searching for the same value in a binary tree.

Solution:
False: A binary search tree could be a linear tree with search in O(n) which is the same as search in
a binary tree.
b) Give one reason why it is helpful for a programmer to think in terms of Abstract Data Types (ADT).

Solution:
It is better to think in terms of ADT because this will eliminate the overhead of how a certain Data
structure is implemented, we do not care about its implementation, but instead we only care about
the Interface that we are going to use.
c) A List ADT can be implemented using either an array or a linked-list. Give one advantage for each
implementation.

Solution:
An advantage of using a linked-list is that, unlike an array, it is not restricted to a size that cannot
be changed after its creation, which means that a link-list is more useful when the size of the data
is not known at the time of creation of the data structure.
An advantage of using an array is having a random access time of O(1), which is useful when
frequent random access to individual elements using an index is needed.
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 2

Exercise 2 (10 Marks)


Consider the following problem. You are given an array of n numbers. The array contains only 0’s and 1’s,
and it is sorted in increasing order. For example, the array might be A = [0, 0, 0, 0, 0, 0, 1, 1, 1].

a) Write an algorithm that prints the index i at which the numbers switch from 0’s to 1’s, i.e. A[i] = 0
and A[i + 1] = 1. In the example above, it should print "5", as A[5] = 0 and A[6] = 1.

Solution:

public static void print(int []a)


{
for(int i=0;i<a.length;i++)
{
if(a[i] == 1)
{
System.out.println(i-1);
break;
}
}
}

b) What is the time complexity of your implementation in part a)?

Solution:
O(n)
c) If the time complexity of your algorithm is O(n) or worse, describe in one short sentence a modifi-
cation to your algorithm that will perform in better that O(n).

Solution:
We can use the concept of binary search so that we check the middle of the array, if it is a zero and
the next value is 1 we print the current index, if it is a zero and the next value is zero too then we
binary search the right half of the array, otherwise we binary search the left half.
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 3

Exercise 3 (10 Marks)


Write a method isLegal(String s) that takes as argument a String s and checks if it is a legal postfix
expression. For example:

• 1 2 + 3 - is legal.
• * 5 4 is not legal.
• 6 7 - 3 / + is not legal.

You are required to use stacks to implement your method.

Solution:

public static boolean isLegal(String s)


{
Stack operands = new Stack();
for(int i=0; i < s.length(); i++)
{
if(Character.isDigit(s.charAt(i)))
{
operands.push(1);
}
else
{
if(operands.isEmpty())
return false;
operands.pop();
if(operands.isEmpty())
return false;
}
}
if(operands.isEmpty())
return false;
operands.pop();
return operands.isEmpty();
}
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 4

Exercise 4 (6 Marks)

a) What does the following code fragment print?

int [] a = new int[3];


IntQueue q = new IntQueue();
for (int b : a)
q.enqueue(b);

while (!q.isEmpty()) {
for (int i = 2; i > q.peek(); i--)
q.enqueue(q.dequeue());
System.out.println(q.dequeue());
}

Solution:

0
0
0

b) What does the following code fragment print?

IntQueue q = new IntQueue();


q.enqueue(0);
q.enqueue(0);
q.enqueue(0);
for (int i = 0; i < 8; i++) {
int c = q.dequeue();
int b = q.dequeue();
int a = q.dequeue();
System.out.println(a + " " + b + " " + c);
c++;
b += c / 2;
a += b / 2;
c = c % 2;
b = b % 2;
a = a % 2;
q.enqueue(c);
q.enqueue(b);
q.enqueue(a);
}

Solution:

0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 5

Exercise 5 (10 Marks)

a) Why is a Binary Search Tree called „Binary“? Why is it convenient for searching?

Solution:
A tree where each node has no more than 2 children is called binary. The search tree is convenient
because at each node you can select which of the two branches to search and completely eliminate
the other - the tree is organized so that one side is always greater, the other less, than the current
node.
If the tree is full and balanced, then you effectively halve the search area with each step, eliminating
one or the other subtree.
b) Given the following inputs sequence.

63 76 81 106 42 51 14 54 16 1 70

1. Construct the corresponding binary search tree by inserting the elements of the sequence
starting from left to right.
Solution:

n 63 PPPP
nnnnn PPP
n nn PPP
nn n PPP
vnnn PP(
42 A 76 A
}} AA }} AA
}} AA }} AA
}} AAA }} AA
~}} ~}} A
14 A 51 A 70 81 ?
{{ AA AA ??
{{ AAA AAA ??
{{ AA AA ??
}{{ 
1 16 54 106

2. Redraw the tree when Node 63 is deleted from the tree.


Solution:

nn 70 RRRRR
n nnnn RRR
RRR
nnnn RRR
nn RR(
vnn
42 A 76 A
}} AA AA
}} AA AA
}} AAA AA
~ }} A
14 A 51 A 81 ?
{{ AA AA ??
{{ AAA AAA ??
{{ AA AA ??
}{{ 
1 16 54 106
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 6

Exercise 6 (12 Marks)


Suppose that linked lists of integers are made from objects belonging to the class

class Node
{
int item;
Node next;
}

The linked list is defined as follows

class LinkedList{

public Node first;

public LinkedList()
{
first = null;
}
}

a) Write a method void organize(int i) that will modify this list, with the elements starting at
index i being split in half. The first half should be placed at the beginning of the list and the second
half at the end of the list. For example, given the list [1, 2, 3, 4, 5, 6, 7] and i = 3, the list
should be modified to [4, 5, 1, 2, 3, 6, 7].
Do not assume the existence of any methods.

Solution:

public void organize(int i)


{
// solution for 0 < i < size - 1
Node current = first;
int size;
for(size = 0; current != null; size++)
current = current.next;
Node a = first, b = first;
for(int j = 1; j < i; j++)
a = a.next;
for(int j = 1; j < i + ((size - i) / 2); j++)
b = b.next;
Node oldFirst = first;
first = a.next;
a.next = b.next;
b.next = oldFirst;
}

b) Re-implement the method organize given that you now supposed to return a new linked list with
the required organization and that you are allowed to use the methods insertFirst, insertLast,
removeFirst, and removeLast of the class LinkedList.

Solution:

public static LinkedList organize(LinkedList l, int i)


{
LinkedList temp = new LinkedList();
int size = 0;
while(!l.isEmpty())
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 7

{
size++;
temp.insertLast(l.deleteFirst().item);
}
for(int j = 0; j < i; j++)
l.insertLast(temp.deleteFirst().item);
LinkedList t = new LinkedList();
for(int j = 0; j < (size - i) / 2; j++)
t.insertLast(temp.deleteFirst().item);
for(int j = 0; j < (size - i) / 2; j++)
l.insertFirst(t.deleteLast().item);
while(!temp.isEmpty())
l.insertLast(temp.deleteFirst().item);
return l;
}
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 8

Exercise 7 (10 Marks)


A Quaternary Search Tree is search tree where each node has at most four children. This tree will be used to
store information about books that are located on a block of shelves in a bookstore. A book has to be to the
right, left, above, or below any other book. Given that a method int locate(Book x, Book y) will
return one of the values 1, 2, 3, 4 meaning that book y is located to the right, left, above, below
compared to book x. Assuming that the time complexity of the locate method is O(1) and that books
are stored in the Quaternary Search Tree using the same concept that is used to store integer values in a
binary search tree. Answer the following questions:

a) What is the worst case time complexity of searching for a book in a Quaternary Search Tree?

Solution:
O(n)
b) What is the worst case time complexity of searching for a book in a Quaternary Search Tree with an
ideal topology, which is defined similarly as the ideal topology of binary search trees presented in
class?

Solution:
O(log n)
c) Assuming that the root of the tree is at level 0 and its children are at level 1, what is the maximum
number of books that can be stored at level 3?

Solution:
64
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 9

Exercise 8 (8 Marks)

a) For a binary search tree (BST) with n items, what is the worse-case running time to find the
maximum difference between any two elements? Justify your answer.
Does the running time depend on whether the binary search tree is balanced? Say why or why not.

Solution:
To find the maximum difference, sufficient to find the minimum element in the BST, the maximum
element in the BST and compute their difference.
Running time depends on the worst-case depth of the minimum and maximum elements in the
BST.
Worst case running time for an unbalanced BST is O(n)
Worst case running time for a balanced BST is O(log(n))
b) Add an instance method to the BinarySearchTree class that swaps all nodes to the right of the
root with all nodes to the left of the root. Does the resulting tree satifies a similar property like the
binary search tree presented in the lecture.

Solution:

public void swap()


{
if(root != null)
{
Node temp = root.left;
root.left = root.right;
root.right = temp;
}
}
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 10

Exercise 9 (8 Marks)
Write a static recursive method

public static boolean sameShape(Tree x, Tree y)

that takes two tree references as inputs and determines whether they have the same tree shape and
pointer structure.

Solution:

public static boolean sameShape(Tree t1, Tree t2)


{
return(sameShape(t1.root,t2.root));
}
public static boolean sameShape(Node x, Node y)
{
if (x == null && y == null) return true; // both null
if (x == null || y == null) return false; // exactly one null
return sameShape(x.left, y.left) && sameShape(x.right, y.right);
}
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 11

Exercise 10 (8 Marks)
In an attempt to describe a family tree we would like to modify the tree implementation presented in
class in order to make nodes represent persons. Each person should be allowed to have an arbitrary (not
predefined) number of children and also have a spouse (another person to which the person is married).

a) What are the instance variables needed to implement the family tree described above?

Solution:
We need two more instance variable:
• A reference to the spouse
• A reference to an array (or some other data structure) of children

class Node
{
Node spouse;
Node [] children;
}

b) Implement a boolean method that checks if every node in the tree and its spouse have the same
children.

Solution:

public boolean check(Node c)


{
if(c != null)
{
Node s = c.spouse;
if(s!=null)
if(c.children != s.children)
return false;
for(int i = 0; i < c.children.length; i++)
if(check(c.children[i]) == false)
return false;
}
return true;
}

c) Implement a boolean method that checks if two given nodes are siblings, i.e. have the same parent.

Solution:

public Node find(Node p, Node c)


{
if(p != null)
if(p.children != null)
{
for(int i = 0; i < p.children.length; i++)
if(c == p.children[i]) return p;
for(int i = 0; i < p.children.length; i++)
{
Node x = find(p.children[i], c);
if(x != null) return x;
}
}
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 12

return null;
}

public boolean siblings(Node c1, Node c2)


{
Node p1 = find(root, c1);
Node p2 = find(root, c2);
if(p1 == p2)
return true;
else
return false;
}
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 13

Exercise 11 (10 Marks)


Consider inserting the keys 104, 221, 316, 444, 6042, 281, 174, 880, 442, 253 into a hash table
of size b = 12 and using the hash function h(x) = sum-of-digitis(x)%b. Use a strategy of your choice to
resolve further collisions.
The function sum-of-digits(n) will sum up the digits of n. For example, if n = 221, then sum-of-digits(221) =
2 + 2 + 1 = 5.

a) What is the strategy that you will use for resolving collisions? Explain the strategy in few words.

Solution:
Linear Probing
b) Insert the keys in the given order in the hash table below.

Solution:

0 444
1 6042
2 174
3 442
4 880
5 104
6 221
7 253
8
9
10 316
11 281
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 14

Extra Sheet
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 15

Extra Sheet
Data Structures and Algorithms, Final Exam, Winter 2006/2007 Page 16

Extra Sheet

You might also like