You are on page 1of 110

‫تجميعات االمتحان النهائي‬ ‫‪Bella‬‬

‫‪Joud‬‬
‫‪M269 - Final‬‬
‫‪2.0‬‬
‫‪Yazeed‬‬

‫بسم هللا الرحمن الرحيم‬

‫حِلف الطالب العصاميين يقدم لكم النسخة الخامسة من تجميعات االمتحانات النهائية محلول ًة بالكامل‪.‬‬
‫جديد النسخة الخامسة‪ :‬إضافة نموذج الفصل الثاني من العام الدراسي ‪ 23-22‬واستدراك األخطاء‪.‬‬
‫مقرر أولى وأكثر أهمية‪.‬‬ ‫نرجو أال تكون هذه التجميعات محل اعتمادكم في المذاكرة‪ ،‬فشرائح ال ُ‬
‫وتعقب وراجع النسخ‪ ،‬ومَن جمع الملفات على مر السنين‪.‬‬ ‫َّ‬ ‫الشكر ُمسدى لكل من صحَح‬
‫يغلب على النماذج تكرار أفكار األسئلة‪ ،‬لذا ننصح بالرجوع إليها واالهتمام بها‬

‫عال‬
‫يب في ِه و َ‬
‫ع َ‬‫ف َج َّل َمن ال َ‬ ‫س َّد ال َخلَال‬
‫عيبًا ف ُ‬ ‫ْ‬
‫وإن ت َ ِج ْد َ‬

‫حرر في‪:‬‬
‫النسخة الخامسة (‪)5‬‬ ‫‪27/11/1444 – 16/6/2023‬‬
‫الفصل الثاني ‪Spring 22-23‬‬
PART 1 Q1 ANSWER:

1. False
2. False
3. True
4. False
5. False
6. False
7. True
8. True
9. True
10. False

PART 2 Q2-A ANSWER:

1.

linear-search: 4 iterations
binary-search: 1 iteration

2.
find the 𝒌𝒕𝒉 largest/smallest element in an unsorted list.

Complexity:

− best-case: O(n)
− worst-case: O(𝑛2 )

3. It’s called collision,

4. O(1)

5. B log log(n)

PART 2 Q2-B ANSWER:

1. O(1)
2. O(n log n)
3. O(n)
4. O(n)
5. O(1)
PART 2 Q3-A ANSWER:

1. Greedy

2. Divide and conquer

3. Brute-force

4. Dynamic

PART 2 Q3-B ANSWER:

− It is necessary to implement the whole algorithm before conducting any experiment.

− Results may not be indicative of the running time on other inputs not included in
the experiment.

− same hardware and software environments must be used.

PART 3 Q4 ANSWER:

a. log 𝑛 ∙ 1 ∙ 𝑛 ⟶ 𝑂(𝑛 log 𝑛)

b. 1 + 1 + log 𝑛 ⟶ 𝑂(log 𝑛)

c. 𝑛 ∙ 𝑛 ∙ log 𝑛 ⟶ 𝑂(𝑛2 log 𝑛)

d.
𝑇(𝑛) = 4𝑇(𝑛/2) + 𝑛
𝑎 = 4, 𝑏 = 2, 𝑑 = 1
𝑎 > 𝑏 𝑑 ⟶ 𝑂(𝑛log2 𝑛 )
= 𝑂(𝑛2 )

e. 𝑛(𝑛 ∙ 𝑛 log 𝑛) ⟶ 𝑛2 + 𝑛2 log 𝑛 ⟶ 𝑂(𝑛2 log 𝑛)


PART 3 Q5 ANSWER:

a)

Euler path; as every vertex have an even degree except two.

b)
− BFS: A B E D F H C G

− DFS: A B D C E F H G

c)
− minimum cost = 2 + 3 + 4 + 4 + 5 + 5 + 8 = 31
− Kruskal's algorithm
− Complexity: O(E log E) or O(E log V)

d)
− Shortest path from A to D: A ⟶ E ⟶ F ⟶ H
− cost: 20

Part 3 Q5-C Spanning tree graph

Iteration Initial 1 2 3 4 5 6 7

Priority From 0 A B C D E F G

A 0 0
B ∞ 5
C ∞ ∞ ∞ 12
D ∞ ∞ 8
E ∞ 14 14 14 14
F ∞ ∞ 20 18 18 16
G ∞ ∞ ∞ ∞ ∞ 20 20
H ∞ ∞ 30 30 30 30 30 20
PART 3 Q5-E ANSWER:

− Floyd-Warshall
− Complexity: O(𝐕 𝟑 )

D0
A B C D E F G H

A 0 5 ∞ ∞ 14 ∞ ∞ ∞
B 5 0 ∞ 3 ∞ 15 ∞ 25
C ∞ ∞ 0 4 8 ∞ ∞ ∞
D ∞ 3 4 0 ∞ 10 ∞ ∞
E 14 ∞ 8 ∞ 0 2 6 ∞
F ∞ 15 ∞ 10 2 0 ∞ 4
G ∞ ∞ ∞ ∞ 6 ∞ 0 5
H ∞ 25 ∞ ∞ ∞ 4 5 0

D1
A B C D E F G H

A 0 5 ∞ ∞ 14 ∞ ∞ ∞
B 5 0 ∞ 3 19 15 ∞ 25
C ∞ ∞ 0 4 8 ∞ ∞ ∞
D ∞ 3 4 0 ∞ 10 ∞ ∞
E 14 19 8 ∞ 0 2 6 ∞
F ∞ 15 ∞ 10 2 0 ∞ 4
G ∞ ∞ ∞ ∞ 6 ∞ 0 5
H ∞ 25 ∞ ∞ ∞ 4 5 0

D2
A B C D E F G H

A 0 5 ∞ 8 14 20 ∞ 30
B 5 0 ∞ 3 19 15 ∞ 25
C ∞ ∞ 0 4 8 ∞ ∞ ∞
D 8 3 4 0 22 10 ∞ 28
E 14 19 8 22 0 2 6 44
F 20 15 ∞ 10 2 0 ∞ 4
G ∞ ∞ ∞ ∞ 6 ∞ 0 5
H 30 25 ∞ 28 44 4 5 0
PART 3 Q6 ANSWER:

a. The algorithm

let A = array of numbers


let B = array of numbers
let n = length of A

let p = power amount

let hashB = hash-map (int --> int)

for i = 1 to n:
hashB[ A[i] ] = B[i]
end of for

sort(A)

for i = 1 to n:
if ( p >= A[i] ):
p += hashB[A[i]]
end of if
end of for
return p

Python code

def findMaximum(n, p, A, B):

hashB = dict()

for i in range(n):

hashB[A[i]] = B[i]

A.sort()

for i in range(n):

if p >= A[i]:

p += hashB[A[i]]

return p

print(findMaximum(5, 8, [128, 64, 32, 16, 8], [128, 64, 32, 16, 8]))
print(findMaximum(3, 10, [20, 30, 10], [9, 100, 10]))

b. complexity: 𝑛 + n log 𝑛 + 𝑛 ⟶ 𝑂(𝑛 log 𝑛)

[note: this is not the only solution, it can be solved with different ideas]
‫الفصل األول ‪Fall 22-23‬‬
PART 1 Q1 ANSWER:

1. False
2. False
3. True
4. True
5. False
6. True
7. True
8. False
9. True
10. False

PART 2 Q2-A ANSWER:

1. When the key is at the first position, or when the list is unsorted.

2.

Linear-search: brute-force

Binary-search: Divide-and-conquer.

3.
Linear-search: 7 iterations
Binary-search: 3 iterations

4. Find the 𝐾𝑡ℎ largest/smallest element in an unsorted list.

5. It’s called collisions.

6. Two techniques: Open addressing, Chaining.

7. O(1)

PART 2 Q2-B ANSWER:

1. Queue
2. Stack
3. Graph
4. Linked List
PART 2 Q2-C ANSWER:

1. O(n)
2. O(n)
3. O(n + m)
4. O(n * m)
5. O(log n)

PART 2 Q3-A ANSWER:

1. Prepositional logic
2. Predicate logic

PART 2 Q3-B ANSWER:

1. P problems
2. NP problems

PART 2 Q3-C ANSWER:

After applying max_heap() the max element will be the first element, so it will not
need any cycle to reach the max.

Part 2 Q3-C graph visualization


PART 2 Q3-D ANSWER:

h(5) = 5 mod 7 = 5
h(28) = 28 mod 7 = 0
h(19) = 19 mod 7 = 5
h(15) = 15 mod 7 = 1
h(20) = 20 mod 7 = 6
h(33) = 33 mod 7 = 5
h(12) = 12 mod 7 = 5
h(17) = 17 mod 7 = 3
h(10) = 10 mod 7 = 3

slot 0: 28
slot 1: 15
slot 2: ---
slot 3: 17 --> 10
slot 4: ---
slot 5: 5 --> 19 --> 33 --> 12
slot 6: 20
PART 3 Q4 ANSWER:

a. 1 + 1 + log n ⟶ O(log n)

b. 1 * 1 * n ⟶ O(n)

[note: assuming the outer loop step is: i *= 2, middle loop step is: j /= 2]

c.

T(n) = 16T(n/4) + O(1)

a = 16, b = 4, d = 0

a > 𝒃𝒅 = 16 > 1

⟶ O(𝒏𝐥𝐨𝐠 𝒃 𝒂 )

⟶ O(𝒏𝟐 )

d.

n * (n + 𝒏𝟐 )

= 𝒏𝟐 + 𝒏𝟑 ⟶ O(𝒏𝟑 )

e.

1 * 1 * log n ⟶ O(log n)

PART 3 Q5 ANSWER:

a)

Euler path; as every vertex have an even degree except two.

b)
− BFS: A B E D F H C G

− DFS: A B D C E F H G
c)
− minimum cost = 2 + 3 + 4 + 4 + 5 + 5 + 8 = 31
− Kruskal's algorithm
− Complexity: O(E log E) or O(E log V)

d)
− Shortest path from A to D: A ⟶ E ⟶ F ⟶ H
− cost: 20

Part 3 Q5-C Spanning tree graph

Iteration Initial 1 2 3 4 5 6 7

Priority From 0 A B C D E F G

A 0 0
B ∞ 5
C ∞ ∞ ∞ 12
D ∞ ∞ 8
E ∞ 14 14 14 14
F ∞ ∞ 20 18 18 16
G ∞ ∞ ∞ ∞ ∞ 20 20
H ∞ ∞ 30 30 30 30 30 20
e) Implement the proper algorithm to find the shortest paths between all pairs of nodes [Compute D0,
D1, D2]. Mention the name of the algorithm that could be used and its complexity (8 marks)

Question 6: (10 marks)


PART 3 Q5-E ANSWER:

− Floyd-Warshall
− Complexity: O(𝐕 𝟑 )

D0
A B C D E F G H

A 0 5 ∞ ∞ 14 ∞ ∞ ∞
B 5 0 ∞ 3 ∞ 15 ∞ 25
C ∞ ∞ 0 4 8 ∞ ∞ ∞
D ∞ 3 4 0 ∞ 10 ∞ ∞
E 14 ∞ 8 ∞ 0 2 6 ∞
F ∞ 15 ∞ 10 2 0 ∞ 4
G ∞ ∞ ∞ ∞ 6 ∞ 0 5
H ∞ 25 ∞ ∞ ∞ 4 5 0

D1
A B C D E F G H

A 0 5 ∞ ∞ 14 ∞ ∞ ∞
B 5 0 ∞ 3 19 15 ∞ 25
C ∞ ∞ 0 4 8 ∞ ∞ ∞
D ∞ 3 4 0 ∞ 10 ∞ ∞
E 14 19 8 ∞ 0 2 6 ∞
F ∞ 15 ∞ 10 2 0 ∞ 4
G ∞ ∞ ∞ ∞ 6 ∞ 0 5
H ∞ 25 ∞ ∞ ∞ 4 5 0

D2
A B C D E F G H

A 0 5 ∞ 8 14 20 ∞ 30
B 5 0 ∞ 3 19 15 ∞ 25
C ∞ ∞ 0 4 8 ∞ ∞ ∞
D 8 3 4 0 22 10 ∞ 28
E 14 19 8 22 0 2 6 44
F 20 15 ∞ 10 2 0 ∞ 4
G ∞ ∞ ∞ ∞ 6 ∞ 0 5
H 30 25 ∞ 28 44 4 5 0
PART 3 Q6-A ANSWER:

− The algorithm

let A = array of numbers


let B = array of numbers
let n = length of A
let hashA = hash-map (int --> int)
let hashA = hash-map (int --> int)
for i = 1 to n:
hashA [ A[i] ] = i
hashB [ B[i] ] = i
end of for

for i=1 to n:
let x =hashA[A[i]]
let y =hashB[B[i]]
print("A[" + x + "] with B[" + y + "]")
end of for

− Python code (‫)غير مطلوب فقط لغرض التوضيح‬

def mugs_linear(A,B):
n = len(A)
hashA = dict()
hashB = dict()
for i in range(n):
hashA[A[i]] = i
hashB[B[i]] = i

for i in A:
print("A[" + str(hashA[i]+1) + "] with B[" + str(hashB[i]+1) + "]")

A = [150, 130, 140, 110, 160, 200, 90, 180, 70]


B = [160, 140, 150, 70, 110, 130, 180, 200, 90]
mugs_linear(A,B)

PART 3 Q6-B ANSWER:

complexity: n + n ⟶ O(n)

[note: this is not the only solution, it can be solved with different ideas]
‫الفصل الصيفي ‪Summer 21-22‬‬
PART 1 Q1-A ANSWER:

1. O(E+V) 6. O(𝑛2 )
2. O(log n) 7. O(2𝑛 )
3. O(n) 8. O(n)
4. O(𝑛3 ) 9. O(V 3)
5. O(1) 10. O(1) | worst case: O(n)

PART 1 Q1-B ANSWER:

1. find the 𝐾𝑡ℎ largest/smallest element in an unsorted list.

2. when the key is at the first position, or when the list is unsorted.

3. it's called collision


two techniques: open addressing, chaining.

4.

linear-search: 7 iterations
binary-search: 3 iterations

5. O(1)

6.

linear-search: brute-force

binary-search: divide-and-conquer

PART 1 Q2-A ANSWER:

1. Logic programming
2. Turing machine
3. NP problem

PART 1 Q2-B ANSWER:

− Software: Software testing can demonstrate the presence of bugs but cannot
demonstrate their absence.

− Components: Although most errors are caused by software, hardware components


do fail.

− Arithmetic: The maximum number of significant digits that can be represented


is limited to a certain value.
Solving part c:
PART 1 Q2-C ANSWER:

1) 3)

T(n) = 8T(n/2) + 2
1 + log n
= O (log n) a = 8, b = 2, d = 1
a > 𝒃𝒅 ⟶ O(𝒏𝐥𝐨𝐠𝒃 𝒂 )
= O(𝒏𝟑 )

2) 4)

T(n-1) + T(n-2) + c
T(n) = 16T(n/2) + 𝑛4
T(n) = 2 T(n-1) + c
T(n-1) = 2 T(n-2) + c a = 16, b = 2, d = 4
T(n-2) = 2 T(n-3) + c a > 𝒃𝒅 ⟶ O(𝒏𝒅 𝐥𝐨𝐠 𝒏)
T(n) = 2[ 2 T(n-2) + c] + c
= O(𝒏𝟒 𝐥𝐨𝐠 𝒏)
T(n) = 2[ 2 [2 T(n-3) +c] +c] +c
T(n) = 2𝑛 + T(1) + c
= O(𝟐𝒏 )

PART 2 Q3 ANSWER:

a.

let start = Array of starting times


let end = Array of ending times
Sort the arrays based on the finishing time
let i = 0
print(start[i])

for j=0 to n-1:


if (start[j] >= end[i])
print(start[j]) i = j
end if
end for

b. Time complexity:

if the array is sorted ⟶ O(n)

if the array is unsorted ⟶ O(n log n)

PART 2 Q4 ANSWER:

a. none of them; there are more than two vertices with odd degrees.

b.
− BFS: A B E F C D
− DFS: A B C D E F

c. minimum cost: 1 + 2 + 2 + 3 + 3 = 11
PART 2 Q4-D ANSWER:

− Time complexity of Dijkstra's algorithm: O(𝐕 𝟐 )

− Shortest path from A to D:


A ⟶ F ⟶ C ⟶ D

− cost: 7

Iteration Initial 1 2 3 4 5

A 0 0
B ∞ 8 8 6 6
C ∞ 4
D ∞ 8 7 7 7 7
E ∞ 7 5 5
F ∞ 3

PART 2 Q5 ANSWER:

1. Selection sort
2. Bubble sort
3. Merge sort
4. Insertion sort
5. Quick sort
PART 2 Q4-E ANSWER:

− Floyd-Warshall

D0
A B C D E F

A 0 8 ∞ ∞ 7 3
B 8 0 2 6 ∞ ∞
C ∞ 2 0 3 ∞ 1
D ∞ 6 3 0 8 5
E 7 ∞ ∞ 8 0 2
F 3 ∞ 1 5 2 0

D1
A B C D E F

A 0 8 ∞ ∞ 7 3
B 8 0 2 6 15 11
C ∞ 2 0 3 ∞ 1
D ∞ 6 3 0 8 5
E 7 15 ∞ 8 0 2
F 3 11 1 5 2 0

D2
A B C D E F

A 0 8 10 14 7 3
B 8 0 2 6 15 11
C 10 2 0 3 17 1
D 14 6 3 0 8 5
E 7 15 17 8 0 2
F 3 11 1 5 2 0
‫الفصل الثاني ‪Spring 21-22‬‬
PART 1 Q1-A ANSWER:

1. O(X.Y)
2. O(1)
3. O(n log n)
4. O(n log n); and O(𝒏𝟐 ) in worst case
5. O(n)
6. O(n)
7. O(n)
8. O(n)
9. O(n)
10. O(E log E) or O(E log V)

PART 1 Q1-B ANSWER:

− Software: Software testing can demonstrate the presence of bugs but cannot
demonstrate their absence.

− Components: Although most errors are caused by software, hardware components do


fail.

PART 1 Q2-A ANSWER:


1)
1. brute-force
2. divide and conquer
3. greedy
4. dynamic

2)
i. brute-force
ii. divide and conquer
iii. greedy

PART 1 Q2-B ANSWER:


1)

1. P problems
2. NP problems

2) -------------------->

PART 1 Q2-C ANSWER:


1. Tree
2. Queue
3. Linked-List
4. Stack
Solving part 3:
PART 1 Q3 ANSWER:

1. none of them, because there are more than two vertices with odd degrees.

2.

− BFS: A B E F C D
− DFS: A B C D E F

3. minimum cost = 1 + 2 + 2 + 3 + 3 = 11

4.

− Time complexity of Dijkstra's algorithm: O( 𝐕 𝟐 )


− Shortest path from A to D: A ⟶ F ⟶ C ⟶ D

Iteration Initial 1 2 3 4 5

A 0 0
B ∞ 8 8 6 6
C ∞ 4
D ∞ 8 7 7 7 7
E ∞ 7 5 5
F ∞ 3

PART 1 Q4-A ANSWER:

i. O(𝒏𝟐 )
ii. O(n log n)

PART 1 Q4-B ANSWER:

A = Array of Integers
n = length of A
greatest = 0
smallest = 999999

for i=0 to n:
if A[i] > longest:
longest = A[i]
else if A[i] < smallest:
smallest = A[i]
end of for
return greatest - smallest

− Time complexity: n + c ⟶ O(n);


There is only one loop

− Why it's better?


because it only takes a time proportional to linear time while the first one takes a
quadratic time and the second takes n-logarithmic time. hence, it's much better.
PART 2 Q3-5 ANSWER:

− Floyd-Warshall

D0
A B C D E F

A 0 8 ∞ ∞ 7 3
B 8 0 2 6 ∞ ∞
C ∞ 2 0 3 ∞ 1
D ∞ 6 3 0 8 5
E 7 ∞ ∞ 8 0 2
F 3 ∞ 1 5 2 0

D1
A B C D E F

A 0 8 ∞ ∞ 7 3
B 8 0 2 6 15 11
C ∞ 2 0 3 ∞ 1
D ∞ 6 3 0 8 5
E 7 15 ∞ 8 0 2
F 3 11 1 5 2 0

D2
A B C D E F

A 0 8 10 14 7 3
B 8 0 2 6 15 11
C 10 2 0 3 17 1
D 14 6 3 0 8 5
E 7 15 17 8 0 2
F 3 11 1 5 2 0
‫الفصل األول ‪Fall 19-20‬‬
PART 2 Q1-A ANSWER:

1. prepositional logic

2. predicate logic

PART 2 Q1-B ANSWER:

1. P problems

2. NP problems

PART 2 Q1-C ANSWER:

1. Linear search: 1 iteration


Binary search: 3 iterations: 90 ⟶ 65 ⟶ 25

2. it finds the kth-smallest item in an unordered list.

3. Collision. techniques to avoid it: Chaining, Open addressing

4. O(1), and O(n) in the worst case.


PART 2 Q2-A ANSWER:

Justification: the third sequence is the correct one; as it follows the binary search
algorithm correctly. i.e. if the key > middle: we eliminate the numbers smaller than
middle, and vice versa.

Taking our selected option (3):


79 > 45: consider smaller
50 > 45: consider smaller
25 < 45: consider greater
26 < 45: consider greater
27 < 45: consider greater
40 < 45: consider greater
44 < 45: consider greater
45 = 45: founded

PART 2 Q2-B ANSWER:

h(5) = 5 mod 7 = 5
h(28) = 28 mod 7 = 0
h(19) = 19 mod 7 = 5
h(15) = 15 mod 7 = 1
h(20) = 20 mod 7 = 6
h(33) = 33 mod 7 = 5
h(12) = 12 mod 7 = 5
h(17) = 17 mod 7 = 3
h(10) = 10 mod 7 = 3

slot 0: 28
slot 1: 15
slot 2: ---
slot 3: 17 ⟶ 10
slot 4: ---
slot 5: 5 ⟶ 19 ⟶ 33 ⟶ 12
slot 6: 20

PART 2 Q2-C ANSWER:

Brute force: Is a very general problem-solving technique that consists of systematically


enumerating all possible candidates for the solution and checking whether each candidate
satisfies the problem's statement. e.g., Selection and insertion sort algorithms…

Greedy Algorithms: The solution is constructed through a sequence of steps. At each step
the next optimal step is selected locally, without considering whether this step leads
to the final global optimal solution or not. e.g., Kruskal, Dijkstra algorithm.

Divide-and-Conquer: Divide the problem instance to several smaller sub-instances then


solve each one independently. Finally, the solutions of these sub-instances are combined
to form final solution. e.g., Merge and quick sort algorithm.
Solving part 3:
PART 3 Q1-A ANSWER:

1. O(𝑛3 )
2. O(𝑛2 * 3𝑛 )
3. O(n log n)
4. O(𝑛3 )
5. O(2𝑛 )

PART 3 Q1-B ANSWER:

n * (n * c + n log n)
= 𝒄𝒏𝟐 + 𝒏𝟐 log n
⟶ O(𝒏𝟐 log n)

PART 3 Q1-C ANSWER:

log n x log n x n
log (𝟐𝒎 ) x log (𝟐𝒎 ) x 𝟐𝒎
m * m * 𝟐𝒎
𝒎𝟐 * 𝟐 𝒎
# m = log n
(𝐥𝐨𝐠 𝒏)𝟐 * n
2log n * n
O(log n * n) ⟶ O(n log n)

PART 3 Q1-D ANSWER:

1.
F(n) = 2F(n-1) + c
F(n) = 2[ 2 T(n-2) + c] + c
F(n) = 2[ 2 [2 T(n-3) +c] +c] + c

⟶ O(𝟐𝒏 )

2.

store the values in a table T and hence avoid calculating it many times, with an
iterative method.

F(n)
{
T[0] = T[1] = 1
for i = 2 to n:
T[i] = T[i-1] + T[i-2]
end of for
return T[n]
}
PART 3 Q2-1-3 ANSWER:

1. Euler path; as every vertex have an even degree except two. hence, we can
traverse the graph visiting each node once.

2. A ⟶ b ⟶ c ⟶ d ⟶ E ⟶ F ⟶ G

3.

− minimum cost: 2+2+5+6+14+15 = 44


− Kruskal's algorithm
− time complexity: O(E log E) or O(E log V)
PART 3 Q2-4 ANSWER:

Iteration Initial 1 2 3 4 5 6

Priority From 0 A F G B C E

A 0 0
B ∞ 10 10 9
C ∞ 30 30 30 15
D ∞ 50 50 50 50 41 38
E ∞ ∞ ∞ ∞ 23 23
F ∞ 5
G ∞ ∞ 7

− complexity: O(𝐕 𝟐 )

− shortest path from A to D: A --> F --> G --> B --> E --> D

− Cost: 38

PART 3 Q3 ANSWER:

a. (n-1) * (n-1) --> O(𝒏𝟐). no, it's not efficient, we can have better complexity.

b. yes; this would minimize the time complexity to be O(n log n) if we use Merge Sort,
or a like.

c.

smallest = arr[0]
largest = arr[0]
for i = 0 to n-1:
if arr[i] > largest:
largest = arr[i]
if arr[i] < smallest:
smallest = arr[i]
end of for
return absolute(largest - smallest)
Fall 19-20 ‫الفصل األول‬
PART 3: Question 1

a) Find the running times of each of the following algorithms and arranges them in increasing
complexity.

[note: your answer should provide a detailed explanation that support your final conclusion]

− Algorithm A: solves problems of size n by dividing them into four sub-problems of size (n/4)
recursively solving each sub-problem and then combining the solutions in constant time.
(take T(1) = 1)

T(n) = 4 T(n/4) + 1
a = 4, b = 4, d = 0
a > 𝑏𝑑

4 > 1, ⟶ O(𝑛log4 4 )
⟶ O(n)

− Algorithm B: solves problems of size n by recursively solving four sub-problems each of size (n/2) and
then combining the solutions in 𝑂(𝑛2) time. (Take T (1) = 0)

T(n) = 4 T(n/2) + 𝒏𝟐
a = 4, b = 2, d = 2
a = 𝑏𝑑

4 = 4, ⟶ O(𝑛𝑑 log 𝑛)
⟶ O(𝑛2 log 𝑛)

− Algorithm C: solves problems of size n by dividing them into three sub-problems of size (n/3)
recursively solving each sub-problem and then combining the solutions in linear time.
(take T(1) = 0)

‫ جودة الصور رديئة في هذا‬:‫مالحظة‬


T(n) = 3 T(n/3) + n
‫ تم إعادة كتابة األسئلة الجـديـدة‬،‫النموذج‬
a = 3, b = 3, d = 1
.‫والمختلفـة عن باقي النماذج‬
a = 𝑏𝑑

3 = 3, ⟶ O(𝑛𝑑 log 𝑛)
⟶ O(𝑛 log 𝑛)

Arrangement: A < C < B


b) Using the (KMP) algorithm,
assume that the pattern is “abacab” and the string is “abacaabaccabacab”.

1. Compute the suffix matrix for the pattern

0 1 2 3 4 5

P[j] a b a c a b
F(j) 0 0 1 0 1 2

2. Draw a figure to illustrate the comparisons that will take place till we find the inside the string.

a b a c a a b a c c a b a c a b

a b a c a b

a b a c a b

a b a c a b

a b a c a b

a b a c a b
‫الفصل الصيفي ‪Summer 18-19‬‬
PART 2 Q1-A ANSWER:

1. O(𝒏𝟐 )
2. O(n log n)
3. O(n)
4. O(n)
5. O(1)
6. O(1)
7. O(mn)
8. O(m + n)
9. O(n)
10. O(n log n)

PART 2 Q1-B ANSWER:

1) When the list is unsorted, small, data structure is not random access (like linked-
list)

2)

Linear search: 7 times because key value is the last element of array
binary search: 3 times

3) Linear search is brute force paradigm, binary search is Divide and Conquer
paradigm.

4) The Quick-select Algorithm will find the kth-smallest item in an unordered list
with a best-case runtime of O(n).

5) Called collision, the solution techniques are Open Addressing (linear Probing) and
Chaining.

6) O(1)
PART 2 Q2-A ANSWER:

i.
Brute force is a general problem-solving technique that consists of
systematically enumerating all possible candidates for the solution and
checking whether each candidate satisfies the problem's statement.

Divide-and-Conquer: Divide the problem instance to several smaller sub


instances then solve each one independently. Finally, the solutions of these
sub-instances are combined to form final solution.
ii.

P problems are questions that have a yes/no answer and can be easily solved
by a computer.

NP problems are questions that have yes/no answers that are easy to verify
but are hard to solve. it would take years, decades, or centuries for your
computer to come up with an answer.

PART 2 Q2-B ANSWER:

space and time.

PART 2 Q2-C ANSWER: (‫)الرسم مطلوب‬

After applying max_heap() the max element will be the first


element, so we don’t need any cycle to reach the max element
as it’s the root.

PART 3 Q1-A ANSWER:


i. ii. iii.

F(n) = 2F(n-1) + c
F(n-1) = 2F(n-2) + c n + 𝑛2 + 𝑛2 + c
log n + c
F(n) = 2[2F(n-2) + c] + c = 2 𝑛2 + n + c ⟶ O(log n)
F(n-2) = 2F(n-3) + c ⟶ O(𝑛2 )
F(n) = 2[2[2F(n-3) + c] + c] + c
F(n) = (2𝑘 ) F(n-k) + ck
K = n , F(0) = F(1) = 1
F(n) = 2𝑛 + F(0) + cn
(n) = 2𝑛 + cn
So, complexity = 2𝑛
⟶ O(2𝑛 )

PART 3 Q1-B ANSWER:


i. ii.
can't be found using Master theorem use back-substitution instead:

T(n-1) = T(n-2) + (n-1)


a = 4, b = 2, d = 1
T(n-2) = T(n-3) + (n-2)
a > 𝑏𝑑 = 4 > 2 T(n-1) = T(n-3) + 2𝑛 – 3
T(n) = T(n-3) + 3𝑛 – 3
⟶ O(𝒏𝐥𝐨𝐠𝒃 𝒂 ) T(n) = T(n-k) + 𝑘𝑛 – k
⟶ O(𝑛𝑛 ) k = n
T(n) = T(n-n) + (n)n - (n)
T(n) = T(0) + 𝑛𝑛 – n
T(n) = 𝑛𝑛 - n ⟶ O(𝒏𝒏 )
Solving part b:

PART 3 Q2-A ANSWER:

− A Tree: a connected, directed acyclic graph.


− A spanning tree: a subgraph of a graph, which meets the constraints to be a tree
(connected, acyclic) and connects every vertex of the original graph.
− A minimum spanning tree: a spanning tree with weight less than or equal to any
other spanning tree for the given graph.

PART 3 Q2-C ANSWER:

O(E log E) or (E log V)


PART 3 Q3-A ANSWER:

set result = 0
for i = 0 to n-2:
for j = i+1 to n – 1:
mult = A[i] * A[j]
if mult > result:
result = mult
end of for
end of for

return result

− complexity: O(𝑛2 )

PART 3 Q3-B ANSWER:

the approach of sorting the array is much better; as it would take us a time
proportional to O (n log n), if we use Merge Sort or a similar algorithm in terms of
time complexity.

PART 3 Q3-C ANSWER:

let firstPos,secondPos = 0
let firstNega,secondNega = 0
for i = 0 to n-1
if arr[i] > firstPos:
secondPos = firstPos
firstPos = arr[i]
else if arr[i] > secondPos:
secondPos = arr[i]
else if arr[i] < firstNega then
secondNega = firstNega
firstNega = arr[i]
else if arr[i] < secondNega then
secondNega = arr[i]

reuslt1 = firstNega * secondNega


result2 = firstPos * secondPos
return Maximum(result1, result2)
‫الفصل الثاني ‪Spring 18-19‬‬
PART 2 Q1-A ANSWER:

1- Greedy algorithm. Ex: Kruskal, Dijkstra algorithm

2- Divide and conquer. Ex: merge and quick sort algorithm

3- Brute Force. Ex: selection and insertion sort algorithms

4- Dynamic programming. Ex: Floyd-Warshall algorithm

PART 2 Q1-B ANSWER:

1- Turing machine is a mathematical model of computation that defines an abstract


machine that operates on an infinite memory tape divided into discrete cells. while
Finite State Machine (FSM) is a mathematical model of computation that can be in
exactly one of a finite number of states at any given time that changes from one
state to another in response to some external inputs.

2- P problems are questions that have a yes/no answer and can be easily solved by a
computer.

Halting problems: Given a program and an input to the program, determine if the
given program will eventually stop with this particular input. If the program
doesn’t stop, then it is in an infinite loop and this problem is unsolvable.

3- Depth First Search (DFS) algorithm traverses a graph in a depthward motion and uses
a stack to remember to get the next vertex to start a search, when a dead end
occurs in any iteration...Breadth First Search (BFS) algorithm traverses a graph in
a breadthward motion and uses a queue to remember to get the next vertex to start a
search, when a dead end occurs in any iteration

PART 2 Q2-A ANSWER:

1-
Linear:4 iterations
Binary:1 iteration

2-

finds the kth smallest element in an unordered list


Complexity (best case): O(n)
PART 2 Q2-A ANSWER: (‫)تابع للحل السابق‬

3- it's called collision,


the techniques are: Open Addressing (linear Probing) and Chaining

4- O(1)

5- log log (n)

PART 2 Q2-B ANSWER:

1. O(𝒏𝟐 )
2. O(n log n)
3. O(n)
4. O(n)
5. O(1)

PART 3 Q1-A ANSWER:


# brute force

result = 0
for i=0 to n-2:
for j=i+1 to n - 2:
if A[j] + A[j+1] > result:
result = A[j] + A[j+1]
end of for
end of for
return result

# Sorting

set n = length of A
sort A
return A[n-1] + A[n-2]

PART 3 Q1-B ANSWER:

the second approach (sorting) is better; is it takes a time proportional to


O(n log n) compared to the brute force approach which takes O( 𝑛2 ).

PART 3 Q1-C ANSWER:

− My approach would be using one loop to iterate over the array, while keeping a
record of the largest number and the second largest number using two variables. At
the end, the sum of those variables is returned.

first = 0
second = 0
for i=0 to n-1:
if arr[i] > first:
second = first
first = arr[i]
if arr[i] > second:
second = arr[i]
end of for
return first + second

− time complexity: O(n)


PART 3 Q2-A ANSWER:

PART 3 Q2 ANSWER:

b. none of them; as there are more than two vertices with odd degrees.

c. A F G B D C E

PART 3 Q2-D ANSWER:

− minimum cost: 2 + 2 + 2 + 4 + 5 + 14 = 29

− time complexity: O(E log E) or O(E log V)


PART 3 Q2-E ANSWER:

Shortest path from A to D: A ⟶ F ⟶ G ⟶ B ⟶ E ⟶ D


Cost = 5 + 2 + 2 + 14 + 15 = 38

Iteration ⟶ Initial 1 2 3 4 5 6

Priority From 0 A F G B C E

A 0 0
B ∞ 10 10 9
C ∞ 30 30 30 15
D ∞ 50 50 50 50 41 38
E ∞ ∞ ∞ ∞ 23 23
F ∞ 5
G ∞ ∞ 7
Fall 18-19 ‫الفصل األول‬

maximum

O(n)

worst case

tree

O(n)
PART 2 Q1-A ANSWER:

1. O(𝒏𝟐 )

2. O(n log n)

3. O(n)

4. O(1)

5. O(1)

6. O(mn)

7. O(m+n)

8. O(V+E)

9. O(E log V)

10. O(log n)

PART 2 Q1-B ANSWER:

Plot d
Plot c
Plot b Plot a

Logarithmic performance Exponential performance Linear performance Constant performance


PART 2 Q1-C ANSWER:

PART 2 Q2-A ANSWER:

1- Brute force: a very general problem-solving technique that consists of systematically


enumerating all possible candidates for the solution and checking whether each
candidate satisfies the problem's statement.

2- Greedy: The solution is constructed through a sequence of steps. At each step the
next optimal step is selected locally, without considering whether this step leads
to the final global optimal solution or not.

3- Divide and conquer: Divide the problem instance to several smaller sub-instances then
solve each one dependently. Finally, the solutions of these sub-instances are combined
to form final solution.

PART 2 Q2-B ANSWER:

1- Logic programming: is a type of programming which is largely based on formal logic.

2- Turing machine: is a mathematical model of computation that defines an abstract


machine that operates on an infinite memory tape divided into discrete cells.

3- NP problems: are questions that have yes/no answers that are easy to verify but are
hard to solve.

4- The Halting problem: Given a program and an input to the program, determine if the
given program will eventually stop with this particular input. If the program doesn’t
stop, then it is in an infinite loop and this problem is unsolvable.
PART 2 Q2-C ANSWER:

Limits on Arithmetic: limitations imposed by the hardware on the representations of both


integer numbers and real numbers.

Limits on Components: Although most errors are caused by software, hardware components
do fail.

Limits of software: Commercial software contains errors. Software testing can demonstrate
the presence of bugs but cannot demonstrate their absence.

PART 3 Q1-A ANSWER:

1- 4 log log n

2- 4 log n

3- (log 𝑛)5 log 𝑛


1
Increasing order

4- (𝑛2 ) (log 4 ) 𝑛

5- 5 n

6- 𝑛4

7- 𝑛log 𝑛

8- 5𝑛

9- 55𝑛
𝑛
10- 𝑛4

[Note: 55𝑛 and 5𝑛 have the same time complexity as they are in same order]
Solving part a:
PART 3 Q1-B ANSWER:

1.

a = 25 b = 5 d = 2
a = 𝑏𝑑 ⟶ 25 = 52
T(n) = O(𝑛𝑑 log n)
= O(𝑛2 log n)

2.

a = 4 b = 5 d = 1
a < 𝑏𝑑 ⟶ 4 < 5
T(n) = O(𝑛𝑑 )
= O(n)

3.

a = 5 b = 4 c = 1
a > 𝑏𝑑 ⟶ 5 > 4
T(n) = O(𝒏𝐥𝐨𝐠 𝒃 𝒂 )
= O(𝑛log4 5 )

4.

1st eq: T(n) = n T(n-1)


2nd eq: T(n) = n[(n-1) T(n-2)]
3rd eq: T(n) = n[(n-1) (n-2) T(n-3)]

the formula is T(n) = n(n-1)(n-2)T(n-3), as n(n-1)(n-2)....1 = N!


T(n) = N! ⟶ O(N!)

5.

1st eq: T(n) = n + T(n-1)


2nd eq: T(n) = n-1 + T(n-2)
3rd eq: T(n) = n-2 + T(n-3)

The formula at step k is:


T(n) = n+(n-1) + (n-2) +...+ (n-k) + T(n-(k+1))
T(n) stops once n-k-1 = 1 ⟶ k = n-2
T(n) = n + (n-1) + (n-2) +...+ (n-k) + 1
Using sum of arithmetic series: n(n+1)/2 = O(𝑛2 )
PART 3 Q1-C ANSWER:

T(n) = 2 T(n-1) + c
T(n-1) = 2 T(n-2) + c
T(n-2) = 2 T(n-3) + c
T(n) = 2[ 2 T(n-2) + c] + c
T(n) = 2[ 2 [2 T(n-3) + c] + c] + c
…. so on till we reach T(2) after n-2 steps
Which lead to an exponential complexity of order O(2𝑛 )

#Design a function

F(n)
{
T[0] = T[1] = 1
for i = 2 to n:
T[i] = T[i-1] + T[i-2]
end of for
return T[n]
}

PART 3 Q2-A ANSWER:

− Kruskal's algorithm
− O(E log E) or (E log V)

PART 3 Q2-B ANSWER:

− Floyd-Warshall Algorithm
− O(𝑉 3 )

A6
A B C D E F

A 0 6 4 7 5 3
B 6 0 2 5 5 3
C 4 2 0 3 3 1
D 7 5 3 0 6 4
E 5 5 3 6 0 2
F 3 3 1 4 2 0
‫الفصل األول ‪Fall 18-19‬‬
PART 2 Q1-A ANSWER:

1. Brute-force: a very general problem-solving technique that consists of


systematically enumerating all possible candidates for the solution and checking
whether each candidate satisfies the problem's statement.

2. Greedy algorithm: The solution is constructed through a sequence of steps. At each


step the next optimal step is selected locally, without considering whether this
step leads to the final global optimal solution or not.

3. Divide and conquer: Divide the problem instance to several smaller sub-instances
then solve each one independently. Finally, the solutions of these sub-instances
are combined to form final solution.

PART 2 Q1-B ANSWER:

1.

− Prepositional logic: the branch of logic that studies ways of joining and/or
modifying entire propositions, statements or sentences to form more complicated
propositions, statements or sentences, as well as the logical relationships and
properties that are derived from these methods of combining or altering statements.

− Predicate logic: a formal language in which propositions are expressed in terms of


predicates, variables and quantifiers.

2.

− P problems: are questions that have a yes/no answer and can be easily solved by a
computer. Example: check if a number is prime.

− NP problems: are questions that have yes/no answers that are easy to verify but are
hard to solve. Example: the travelling salesman problem

PART 2 Q1-C ANSWER:

limitations:
− It is necessary to implement the whole algorithm before conducting any experiment,
which may be difficult.

− The same hardware and software environments must be used.


Solving part c:
PART 2 Q2-A ANSWER:

If the list is initially unsorted, small, and data structure is not random accessed.
Also, if the key is at the first position in the list.

PART 2 Q2-B ANSWER:

Linear: 7 iterations
Binary: 3 iterations

PART 2 Q2-C ANSWER:

linear search: brute force


Binary search: divide and conquer

PART 2 Q2-D ANSWER:

Quickselect finds the kth smallest element in an unordered list using the same overall
approach as Quicksort, by choosing one element as a pivot and partitioning the data in
two based on the pivot, accordingly as less than or greater than the pivot.

PART 2 Q2-E ANSWER:

it's called collision,


The techniques are: Open Addressing (linear Probing) and Chaining

PART 2 Q2-F ANSWER:

O(1)

PART 3 Q1-A ANSWER:


#ALGORITHM:

for i from 0 to size-2:


for j from 0 to size - i - 2:
if arr[j] is white and arr[j+1] is black:
swap arr[j] and arr[j+1]
# Python code just for reference:

lists=[1,0,1,1,0,0,1,0,0,0,1,0,1]
for i in range (0,len(lists)-2):
for j in range(0,len(lists)-i-2):
if lists[j] > lists[j+1]:
lists[j],lists[j+1] = lists[j+1],lists[j]
print(lists)

PART 3 Q1-B ANSWER:

complexity is O(𝑛2 ) since there are two nested for loops.


PART 3 Q2-A ANSWER:

− purpose: find the minimum cost spanning tree.


− type: greedy algorithm

PART 3 Q2-B ANSWER:

1. Remove all loops and Parallel Edges from the given graph.

2. Arrange all edges in their increasing order of weight.

3. Add the edge which has the least weightage, while checking that the spanning
properties remain intact.

PART 3 Q2-C ANSWER:

minimum cost: 2 + 3 + 4 + 5 + 5 = 19

PART 3 Q3-A ANSWER:

i. Three nested loops:


O(1) * O(n) * O(log n) = O(n log n)

ii. Two separate loops:


O(1) + O(n) = O(n)

PART 3 Q3-B ANSWER:

Expression Big-O Order


2
10 𝑛2 log 𝑛 O(𝑛 log n) 4
100 n + 2 n log n O(n log n) 2
10 n/2 O(n) 1
3𝑛2/10 + 2𝑛2 O(𝑛2 ) 3

PART 3 Q3-C ANSWER:

Every time we invoke BinDig(), we are dividing n by 2, and adding 1 to BinDig(n/2).


Therefore, we have 2 arithmetic operations.
T(n) = 2+T(n/2), which T(1)= 1

since b > 0, by using Master Theorem:


a = 1 b = 2 d = 0
𝑑
a = 𝑏 ⟶ 1 = 1
T(n) = O(𝑛𝑑 log n)
= O(𝑛0 log n)
he complexity is O(log n)
PART 3 Q4-A ANSWER:

PART 3 Q4-B ANSWER:

DFS: 1 ⟶ 2 ⟶ 3 ⟶ 4 ⟶ 6 ⟶ 5 ⟶ 7 ⟶ 8

PART 3 Q4-C ANSWER:

BFS: 1 ⟶ 2 ⟶ 3 ⟶ 4 ⟶ 6 ⟶ 5 ⟶ 7 ⟶ 8
Summer 17-18 ‫الفصل الصيفي‬
PART 1: ALL QUESTIONS ARE REQUIRED [20 Marks]

Mark the following statements are true or false: (20 marks, 2 mark each)
1) The Worst-case time complexity of a linear search algorithm occurs when the requested
item is The last element in the array, or not there at all
2) In the breadth first traversal we process all of a vertex’s descendants before we
move to an adjacent vertex.
3) Arrays are best data structures for relatively permanent collections of data.
4) The linked list is a linear data structure.
5) Compared to doubly linked lists, singly-linked lists require less space.
6) To represent hierarchical relationship between family members, a graph data
structure is suitable.
7) Any node in the path from the root of a tree data structure to the destination node is
called ancestor node.
8) A graph is a collection of nodes, called varices and line segments called edges that
connect pair of nodes.
9) In linear search, search start at the beginning of the list and check every element in the
list.
10) The complexity of the binary-search algorithm is O(n log n).

PART 2: ALL QUESTIONS ARE REQUIRED [40 Marks]

Question 1: (10 marks)

i. Differentiate between the following pairs of terminologies. Your answer should include a
brief description for each of them and supported by an example.
i) Brute force & Divide-and-Conquer paradigms. (4 marks)
ii) P and NP type of problems. (4 marks)
ii. What are the main concerns that should be considered when designing an efficient algorithm?
(2 marks)
Question 2: (10 marks)

a) Explain what is meant by Hash-table data structure and what is meant by Collison. Then explain the
difference between linear probing and chaining method. (4 marks)
b) Draw the 11-entry hash table that results from using the hash function, h(i) = (3i+5) mod 11,
to hash the keys 12, 44, 13, 88, 23, 94, 11, 39, 20, 16, and 5.
i) assuming collisions are handled by chaining. (3 marks)
ii) assuming collisions are handled by linear probing. (3 marks)

Question 3: (10 marks)

Given the following array A [7,12,4,9,19,2,6,8,11,15,20,5,3], answer the following set of questions.
a) Draw the heap presentation of this array (2 marks)
b) What is the depth of node 19? (2 marks)
c) Find the sibling(s) nodes(s) of node 20. (2 marks)
d) Find the pre-order traversal of this tree. (4 marks)
PART 2 Q1-A ANSWER:

i)
Brute force: Is a very general problem-solving technique that consists of systematically
enumerating all possible candidates for the solution and checking whether each candidate
satisfies the problem's statement. e.g., Selection and insertion sort algorithms…

Divide-and-Conquer: Divide the problem instance to several smaller sub-instances then


solve each one independently. Finally, the solutions of these sub-instances are combined
to form final solution. e.g., Merge and quick sort algorithm.

ii)
P problems are questions that have a yes/no answer and can be easily solved by a
computer.

NP problems are questions that have yes/no answers that are easy to verify but are hard
to solve. it would take years, decades, or centuries for your computer to come up with
an answer.

PART 2 Q1-B ANSWER:

time complexity and memory space complexity.

PART 2 Q2-A ANSWER:

− Hash table: A data structure which stores data in an associative manner.


− Collison: Multiple keys hashed to the same slot.

o Linear probing: all elements stored in hash table itself. When collisions
occur, use a systematic procedure to store elements in free slots of the
table.

o Chaining: Store all elements that hash to the same slot in a linked list and
store a pointer to the head of the linked list in the hash table slot.

PART 2 Q2-B ANSWER:

h(12) = (3 × 12 + 5) mod 11 = 8
h(44) = (3 × 44 + 5) mod 11 = 5
h(13) = (3 × 13 + 5) mod 11 = 0
h(88) = (3 × 88 + 5) mod 11 = 5
h(23) = (3 × 23 + 5) mod 11 = 8
h(94) = (3 × 94 + 5) mod 11 = 1
h(11) = (3 × 11 + 5) mod 11 = 5
h(39) = (3 × 39 + 5) mod 11 = 1
h(20) = (3 × 20 + 5) mod 11 = 10
h(16) = (3 × 16 + 5) mod 11 = 9
h(5) = (3 × 5 + 5) mod 11 = 9
i. By chaining:

slot 0: 13
slot 1: 94 ⟶ 39
slot 2: ---
slot 3: ---
slot 4: ---
slot 5: 44 ⟶ 88 ⟶ 11
slot 6: ---
slot 7: ---
slot 8: 12 ⟶ 23
slot 9: 16 ⟶ 5
slot 10: 20

ii. By linear probing:

slot 0: 13
slot 1: 94
slot 2: 39
slot 3: 16
slot 4: 5
slot 5: 44
slot 6: 88
slot 7: 11
slot 8: 12
slot 9: 23
slot 10: 20

PART 2 Q3-A ANSWER: Using Max_Heapify (‫)إذا طلب الترتيب في السؤال نستخدم هذا الحل‬

PART 2 Q3-B ANSWER: 1

PART 2 Q3-C ANSWER: None

PART 2 Q3-D ANSWER:

Pre-Order: 20, 19, 11, 8, 9, 15, 7, 12, 6, 5, 2, 3, 4


PART 2 Q3-A ANSWER: Using Heap only

PART 2 Q3-B ANSWER: 2

PART 2 Q3-C ANSWER: 15

PART 2 Q3-D ANSWER:

Pre-Order: 7, 12, 9, 8, 11, 19, 15, 20, 4, 2, 5, 3, 6


Question 4: (10 marks)

a) Explain what is meant by Euler path and Euler circuit? and state the condition(s) that
should exist for a finite graph in order to have Euler path or Euler circuit. (4 marks)
b) Convert the figure below to a graph and show any existing Euler path or Euler circuit. (4 marks)
c) Select only one bridge that you can remove in order to create Euler path, and explain (4 marks)
your answer.

PART 3: ALL QUESTIONS ARE REQUIRED [40 Marks]

Question 1: (12 marks)

Consider the following function:

𝑛−1

𝐹(𝑛) = ∑ 𝐹(𝑖)𝐹(𝑖 − 1) 𝑓𝑜𝑟 𝑛 > 1 𝑤𝑖𝑡ℎ 𝐹(0) = 𝐹(1) = 2


𝑖=1

Consider T(n) to be the number of arithmetic operations used to compute the functions.
a) Show that a direct recursive algorithm would give an exponential complicity. (4 marks)
b) Design an algorithm, by not re-computing the same F(i) value twice, so that you can (4 marks)
obtain an algorithm with T(n) = O (𝑛2 ).
c) Update your algorithm to achieve T(n) = O(n) if possible. (4 marks)

Question 2:(10 marks)

Fill the table below with the Big-O notation and the order (which is a number from 1 to 5, where 1
represents the asymptotically smallest and 5 represents the asymptotically largest):

Expression Big-O Order


2 𝑛2 − log 𝑛/7
1000 𝑛2 log 2𝑛
1000 𝑛 log 8 + 30 𝑛
10 𝑛 × 40 log 𝑛
1000000
PART 2 Q4-A ANSWER:

− Euler path: a graph is a simple path containing every edge of the graph.
− Euler circuit: a graph is a simple circuit containing every edge of the graph.

Conditions:

Theorem 1: A finite graph has an Euler circuit if and only if it is connected and all
vertices have even degree.

Theorem 2: A finite graph has an Euler path (but not an Euler circuit) if and only if
it is connected and exactly two vertices have odd degrees.

PART 2 Q4-B ANSWER:

none of them; there are more than two vertices with odd degrees.

PART 2 Q4-C ANSWER:

remove the bridge 𝐸−𝐶; then there will be exactly two vertices with odd degrees.
PART 3 Q1-A ANSWER:

To solve this problem, we have to understand how the F(n) is calculated. So for
example if we want to compute F(5) the following tree of calculation is needed

------ N = 5

------ N = 4

------ N = 3

------ N = 2

------ N = 1

In this recursion tree, each state (except f(0) and f(1)) generates two additional
states and total number of states generated are 15. In general, total number of states
are approximately equal to 2𝑛 for computing n'th number(f(n)). Notice that each state
denotes as f(i) which does nothing but to make another recursive call. Therefore, total
time taken to compute nth number of f(n) sequence is O( 2𝑛 ).

PART 3 Q1-B ANSWER:

Using a table T[] and with complexity O(𝑛2)

F(n)
{
T[0] = T[1] = 2;
for i = 2 TO n
{
T[i] = 0;
For k = 1 TO i-1
{
T[i] = T[i] + T[k] * T[k-1];
}
}
return T[n];
}

PART 3 Q1-C ANSWER:

# Using a table T[] and with complexity O(𝑛)

F(n)
{
T[0] = T[1] = 2;
for i = 2 TO n
T[i] = T[i-1] + T[i-1] * T[i-2];
return T[n];
}
Question 3: (10 marks)

1. Use Master Theorem to find the O notation for the following recurrence relations.
[Note: your answer must show the steps that lead to your final answer]

i) T(n) = 4T(n/2) + n (2 marks)


ii) T(n) = T(n/2) + n (2 marks)
iii) T(n) = 4T(n/2) + 𝑛3 (2 marks)

2. Find the complexity of the following blocks of code, where A, B are arrays, n is the input size:

[Note: your answer must show the steps that lead to your final answer]

i) for i = 1 to n Do
A[i] = 1 / i
endfor
SelectSort(A, n)
for i = 1 to n Do
B[i] = 𝑖2
endfor
MergeSort(B, n) (2 marks)

ii) i=1
while i < 100 do
i=2xi
endwhile
j=1
while j < n do
j=2xj
endwhile (2 marks)
PART 3 Q2 ANSWER:

Expression Big-O Order


2
2 𝑛2 − log 𝑛/7 𝑛 4
2
1000 𝑛2 log 2𝑛 𝑛 log 𝑛 5
1000 𝑛 log 8 + 30 𝑛 𝑛 2
10 𝑛 × 40 log 𝑛 𝑛 log 𝑛 3
1000000 1 1

PART 3 Q3 ANSWER:

a.
i.
𝑇(𝑛) = 4𝑇(𝑛/2) + 𝑛

𝑎 = 4, 𝑏 = 2, 𝑑=1

𝑎 > 𝑏𝑑 ⟶ 𝑂(𝑛log2 4 )

= 𝑂(𝑛2)

ii.
𝑇(𝑛) = 𝑇(𝑛/2) + 𝑛

𝑎 = 1, 𝑏 = 2, 𝑑=1

𝑎 < 𝑏𝑑 ⟶ 𝑂(𝑛𝑑)

= 𝑂(𝑛)

iii.
𝑇(𝑛) = 4𝑇(𝑛/2) + 𝑛3

𝑎 = 4, 𝑏 = 2, 𝑑=3

𝑎 < 𝑏𝑑 ⟶ 𝑂(𝑛𝑑)

= 𝑂(𝑛3)

b.

i. 𝑛 + 𝑛2 + 𝑛 + 𝑛𝑙𝑜𝑔𝑛 ⟶ 𝑂(𝑛2)
ii. 1 + log 𝑛 ⟶ 𝑂(log 𝑛)
Question 4: (8 marks)

Consider the following weighted graph with 9 vertices and 19 edges. Note that the edge weights
are distinct integers between 1 and 19.

Solving part b:

a) Explain what is meant by tree, spanning tree, and minimum spanning tree? (3 marks)
b) Find the minimum spanning tree for this graph using Kruskal’s algorithm. (3 marks)
c) What is the complexity of this algorithm? (2 marks)

End of Questions
PART 3 Q4 ANSWER:

a.
− A Tree: a connected, directed acyclic graph.

− A spanning tree: a subgraph of a graph, which meets the constraints to be a


tree (connected, acyclic) and connects every vertex of the original graph

− A minimum spanning tree: a spanning tree with weight less than or equal to
any other spanning tree for the given graph.

c. 𝑂(𝐸 𝑙𝑜𝑔 𝐸) 𝑜𝑟 (𝐸 𝑙𝑜𝑔 𝑉)


‫الفصل الثاني ‪Spring 17-18‬‬
PART 2 Q1 ANSWER:

− Brute force is a general problem-solving technique that consists of systematically


enumerating all possible candidates for the solution and checking whether each
candidate satisfies the problem's statement. example: Selection and insertion sort
algorithms.

− Greedy algorithms: the solution is constructed through a sequence of steps. At each


step the next optimal step is selected locally, without considering whether this step
leads to the final global optimal solution or not. example: Kruskal and Dijkstra
algorithms.

− Divide-and-Conquer: divide the problem instance to several smaller sub instances then
solve each one independently. Finally, the solutions of these sub-instances are
combined to form final solution. example: Merge and quick sort algorithms.

PART 2 Q2-A ANSWER:

− The naïve approach for solving the string searching problem by performing Brute-
Force comparison of each character in the pattern at each possible placement of the
pattern in the string. O(mn)

− KMP is algorithm compares the pattern to the text in left-to-right but shifts the
pattern more intelligently than Brute-Force. O(m+n)

PART 2 Q2-B ANSWER:

− Depth First Search (DFS) algorithm traverses a graph in a depthward motion and uses
a stack to remember to get the next vertex to start a search. O(n+m)

− Breadth First Search (BFS) algorithm traverses a graph in a breadth ward motion and
uses a queue to remember to get the next vertex to start a search. O(n+m)

PART 2 Q2-C ANSWER:

− Kruskal's algorithm to find the minimum cost spanning tree uses the greedy approach.
O(E log E) or O(E log V)

− Dijkstra's algorithm finds shortest (minimum weight) path between a particular pair
of vertices in a weighted directed graph with nonnegative edge weights. O(V 2)

PART 2 Q3-A ANSWER:

The minimum heap makes the key of a node is ≤ the keys of its children. So, min-heapify
function corrects a single violation of the heap property in a subtree at its root.

PART 2 Q3-B ANSWER:

1. Build Min Heap from unordered array.


2. Find minimum element A[1];
3. Swap elements A[n] and A[1]
4. Discard node n from heap
5. Run minimum_heapify.
6. Go to Step 2 unless heap is empty

PART 2 Q3-C ANSWER: Heap-sort is O(n log n)


PART 3 Q1-A ANSWER:

PART 3 Q1-B ANSWER:

a spanning tree with weight less than or equal to any other spanning tree for the
given graph.

PART 3 Q1-C ANSWER:

PART 3 Q2-A ANSWER:

multip(A,B):
for i=0 to n-1:
for j=0 to n-1:
result = 0
for k = 0 to n-1:
result = result + A[i][k] * B[k][j]
end of for
C[i][j] = result
end of for
end of for
return C

PART 3 Q2-B ANSWER:

T(n) = (n)(n)(n) + c
⟶ O(𝑛3 )
PART 3 Q3-A ANSWER:

let V = number of vertices


let A = V x V array of distances
for k=0 to V-1:
for i=0 to V-1:
for j = 0 to V-1:
if (A[i][j] > (A[i][k] +A[k][j]) ) :
A[i][j] = A[i][k] +A[k][j]
end of for
end of for
end of for

PART 3 Q3-B ANSWER: O(V 2)

PART 3 Q3-C ANSWER:

D1
A B C D

A 0 ∞ 3 ∞
B 2 0 5 ∞
C ∞ 7 0 1
D 6 ∞ 9 0

D2
A B C D

A 0 ∞ 3 ∞
B 2 0 5 ∞
C 9 7 0 1
D 6 ∞ 9 0

D3
A B C D

A 0 10 3 4
B 2 0 5 6
C 9 7 0 1
D 6 16 9 0

D4
A B C D

A 0 10 3 4
B 2 0 5 6
C 9 7 0 1
D 6 16 9 0
PART 3 Q4 ANSWER:

a) b) c)

since they are three nested since they are two non- since they are nested:
loops: nested loops then 1 + n
n * n * log n ⟶ 𝑛2 log n 1 * n * log n

complexity: O(𝑛2 log n)


complexity: O(n) so total complexity: O(n log n)
Fall Mock Final Exam 22-23

PART 1: ALL QUESTIONS ARE REQUIRED [xx Marks]

Mark the following statements are true or false: (xx marks, 1 mark each)

1) Arrays are best data structures for frequently changing collections of data (F)
2) The Worst-case time complexity of a linear search algorithm occurs when the requested
item is The last element in the array, or not there at all. (T)
3) The Tree is a linear data structure. (F)
4) Compared to singly-linked lists, doubly linked lists require more space. (T)
5) To represent hierarchical relationship between family members, a graph data structure is
suitable. (F)

PART 2: ALL QUESTIONS ARE REQUIRED [xx Marks]

Example of Questions in such part

Question:
What is the complexity of the following tasks? Why?
1) Sorting a list of N elements using Selection-Sort algorithm.
2) Finding the largest element in a queue of size n+3.
3) Finding the smallest element in a linked-list of size n.

Answer:
What is the complexity of the following tasks?
(1 mark for the complexity and 1 mark for the rationale per each)
1) O(n2): because the selection sort complexity is O(n2)
2) O(n): because finding the largest element in a queue involve traversing the whole queue of
size n
3) O(n): because finding the smallest element involve traversing the whole linked list of size n

Question:
Differentiate between the following pairs of terminologies. Your answer should include a brief
description for each of them and supported by an example.
i) Brute force & Divide-and-Conquer paradigms. (4 marks)
ii) P and NP types of problems. (4 marks)

Answer:
(Marking guide: 1 mark for each description and 1 for each example)

Page 2 of 8
i) Brute force: is a straightforward approach to solving a problem, usually directly based on
the problem statement and definitions of the concepts involved. e.g. selection and insertion
sort algorithms.
Divide-and-Conquer: Divide the problem instance to several smaller sub-instances then
solve each one independently. Finally, the solutions of these sub-instances are combined to
form final solution. e.g. Merge and quick sort algorithm.
ii) P problems are problems that have a yes/no answer and can be easily solved by a
computer. For example, determining whether a number is prime or not.
NP problems are problems that have yes/no answers that are easy to verify, but are hard to
solve in the sense that it would take years, decades or centuries for your computer to come
up with an answer. For example, the travelling salesman problem is trying to figure out the
shortest trip through a bunch of cities, visiting each city only once

What are the main concerns that should be considered when designing an efficient algorithm?

Answer:
a) The solution should focus on 1) time complexity 2) memory space and how to keep them both
as minimum as possible. (2 marks)

Question:

How the following array [9,8,23,14,17] will look like after applying Build_ Max Heap function?
Once this function is implemented, how many cycle it would take to get the maximum element in
this array? (5 marks)

Answer:
The array will look like this: [23,17,9,14,8] (3marks)
It will not need any cycle as the maximum element will be at the first element on the array. (2
marks)

PART 3: ALL QUESTIONS ARE REQUIRED [xx marks]

Examples of Questions in such part

Question:

A following weighted graph contains 6 vertices


and 10 edges

a) Does this graph contain Euler circuit


or/and Euler path? Why? (8 marks)
b) What is the sequence of visited node in
BFS, and DFS if both algorithms start
from node A? (8 marks)
c) Draw the minimum spanning tree of this
graph. Mention the name of the algorithm

Page 3 of 8
that could be used and its complexity (8 marks)

d) Use the Dijkstra's algorithm to determine the


shortest paths from node (A) to all other iteration  Initial 1 2 3 4 …
cities (5 marks). Determine the shortest
Priority From 0 A
path and cost from node A to node D (2
marks). A 0 0
[Hint: Using the table below, implement B ∞
the algorithm step by step to show which C ∞
node will be added in sequence] D ∞
E ∞
F ∞

e) Determine the shortest paths between all pairs of nodes. Mention the name of the algorithm
that could be used and its complexity (16 marks)

Answer:
a) The graph has neither Euler path nor Euler circuit. This is because the connected graph has
more than two vertices with odd degrees. (4 marks: foe the decision, and 4 marks for the
reason)
b) BFS: A, B, E, F, C, D (4 marks)
DFS: A, B, C, D, E, F (4 marks)
c) [Marking guide: 8 marks total: 4 marks for the graph, 2 marks for the name of the algorithm,
and 2 marks for the complexity]
The minimum spanning tree of the graph is as follows:

Sorted Length Accepted


Edges / Rejected
FC 1 √
CB 2 √
FE 2 √
AF 3 √
CD 3 √
FD 5 x
BD 6 x
AE 7 x
AB 8 x
ED 8 x

The Kruskal's algorithm is the one that could be used to solve this problem, and it complexity
is O(E log E) or O(E log V) where E is the set of edges and V is the set of vertices.

Page 4 of 8
d) The Dijkstra's algorithm

iteration  Initial 1 2 3 4 5

Priority From 0 A F C B
A 0 0 0 0 0 0
B ∞ 8 8 6 6
C ∞ ∞ 4
D ∞ ∞ 8 7 7 7
E ∞ 7 5 5
F ∞ 3
(5 marks)
The path from node A to D is: A F  C  D (1 mark)
The cost is: 7 (1 mark)
[
e) Marking guide: 16 marks total: 2 marks for the name of the algorithm, 2 marks for the
complexity, and the rest 12 marks are explained below]
To find the shortest paths between all pairs of nodes we can use the Floyd–Warshall algorithm
with complexity O(V3), where V is the set of vertices.

[Finding the shortest path between all pairs of nodes: 12 marks]


Applying the algorithm results in the following matrices:

D0 A B C D E F
A 0 8   7 3
B 8 0 2 6  
C  2 0 3  1
D  6 3 0 8 5
E 7   8 0 2
F 3  1 5 2 0

D1 A B C D E F D2 A B C D E F
A 0 8   7 3 A 0 8 10* 14* 7 3
B 8 0 2 6 15* 11* B 8 0 2 6 15 11
C  2 0 3  1 C 10* 2 0 3 17* 1
D  6 3 0 8 5 D 14* 6 3 0 8 5
E 7 15*  8 0 2 E 7 15 17* 8 0 2
F 3 11* 1 5 2 0 F 3 11 1 5 2 0
(2 marks) (2 marks)

Page 5 of 8
D3 A B C D E F D4 A B C D E F
A 0 8 10 13* 7 3 A 0 8 10 13 7 3
B 8 0 2 5* 15 3* B 8 0 2 5 13* 3
C 10 2 0 3 17 1 C 10 2 0 3 11* 1
D 13* 5* 3 0 8 4* D 13 5 3 0 8 4
E 7 15 17 8 0 2 E 7 13* 11* 8 0 2
F 3 3* 1 4* 2 0 F 3 3 1 4 2 0
(2 marks) (2 marks)

D5 A B C D E F D6 A B C D E F
A 0 8 10 13 7 3 A 0 6* 4* 7* 5* 3
B 8 0 2 5 13 3 B 6* 0 2 5 5* 3
C 10 2 0 3 11 1 C 4* 2 0 3 3* 1
D 13 5 3 0 8 4 D 7* 5 3 0 6* 4
E 7 13 11 8 0 2 E 5* 5* 3* 6* 0 2
F 3 3 1 4 2 0 F 3 3 1 4 2 0
(2 marks) (2 marks)

Question

Find the complexity of the following algorithms, where A, B are arrays, n is the input size:
[Note: your answer must show the steps that lead to your final answer]
i) def F(n):
if n == 0:
return 0
elif n == 1:
return 1
else: return F(n-1) + F(n-2) (2 marks)

ii) for i = 1 to n Do
A[i] = 1 / i
B[i] = i2
endfor
InsertionSort(A, n)
BubbleSort(B, n) (2 marks)

b) Use the appropriate method to find the O notation for the following recurrence relations.
[Note: your answer must show the steps that lead to your final answer] (2 marks each)
i) T(n) = 4T(n/2) + n
ii) T(n) = T(n-1) + n for n > 0 with T(0) = 0

Answer:

a) i) The complexity of the function is  O(2n) this is


because the calculation of F(4) as example
will involve the following calculations:
(2 marks)

Page 6 of 8
ii) O(n) + O(n2) + O(n2) = O(n2) (2 marks)

b) i) using master theory


a = 4, b = 2, d = 1, a > bd T(n)  (n log 2 4 )  (n 2 ) (2 marks)
ii) using back substitution method
T(n) = implement the back substitution step by step
n(n+1)/2  (n2 ) (2 marks)

Question
Given an array of unsorted integers, find the maximum product of two integers in an array,
assuming that all values in the array are non-negative. For example, if the arr = [5, 3, 4, 2, 9] then
the maximum product would be = 45, as 5 and 9 are the bigger integers in this given array and
hence their product will be the answer. To solve this problem, the following idea can be used:

Answer the following questions:


a) One of the solutions is to: "Consider every pair in the given array and return the maximum
product". Transform this idea to an algorithm (Pseudocode) and find its complexity. (5
marks)
b) Another solution would be: "Sort the array first, and then to get the product of its highest
two integers". Is this idea better that the first one? Why? (5 marks)
c) Design your own idea to solve this problem in O(n) complexity, where n is the size of the
array. [note: your idea should be explained in simple English, and then transformed into
algorithm (pseudocode)]. (5 marks)
Answer:

a) [Marking guide: 5 marks total: 3 marks for the algorithm, 2 marks for the complexity]

The first algorithm will be as follows: (3 marks)


Max = arr [0] * arr[1] // Max as default value
For i = 0 to n-2 // nested loop to roll over all
For j = i+1 to n-1 // possible pairs
Prod = arr[i] * arr[j] // get the product of each pair
If Prod > Max // check if it is bigger than the Max
Max = Prod // update Max if yes
return Max
Guide: the student can also explain the algorithm in steps

The complexity of the algorithm is O(n2) as it require two nested for loops (2 marks)

b) [total 5 marks: The answer should critic each of them apart (2 marks), mention the complexity
as a main criterion of comparison (2 marks), and concluding which is the better (1 mark)]

The first idea is the naïve solution where all possible pairs are tested resulting in O(n 2)
complexity. The second solution is more smart by implementing a Sort() function with
complexity that could be O(n log n) and then getting the product of the last two cells resulting
a total complexity O(n log n), which is better than the first idea.

Page 7 of 8
c) [total 5 marks: The answer should an idea explained in simple English (2 marks), and then
the algorithm (3 marks)]

The proposed idea can be as follows: (2 marks)


Idea: To get the highest 2 elements in the array using one for loop with complexity O(n)
and then to multiply them, without the need to sort the whole array.

The algorithm will be as follows: (3 marks)

Max1 = max(arr[0], arr[1]) // Max1 as default value


Max2 = min(arr[0], arr[1]) // Max2 as default value
For i = 2 to n-1 // loop over the rest of the array
If (arr[i] > Max1) Max1= arr[i] // update Max1 (if possible)
elseIf (arr[i] > Max2) Max2= arr[i] // update Max2 (if possible)
Max = Max1 * Max2 // get Max by the end of the loop
return Max

End of the mock exam

General advices:
1- You are not obligated to answer all the questions in order. Be smart in distributing your
exam time, start with the questions that are easy for you, and earn more marks.
2- Organizing your answers and enhancing your handwriting is something important.
3- Solve by hand all the examples provided in the lectures before entering the exam in order
to be well ready and avoid wasting precious time during the exam.
4- If you are requested to provide efficient algorithm to solve a specific problem, ask
yourselves first whether using sorting, or searching techniques will help, then think of using
special data structure. In case you fail, you can at least provide the brute force solution to
avoid losing the whole mark.

End of the Document

Page 8 of 8
Part 1: [50 Marks]
Question 1: (25 marks)

a) Give a brief answer to the following questions: (10 marks)


1) What is the name of the algorithm that is able to find the rth biggest element in a
random list (1 mark)?
2) What is the word used to describe the completion of two elements for the same
cell in the hash table, list two methods to avoid this situation? (3 marks)
3) What is the search complexity in an array sorted by bubble algorithm? (1 mark)
4) Arrange the complexities of the following operations (from worst to best): best to worse
5 n2, n log 10, 1000 n, 100 log n, 2n, 100 log 64. (2 marks)
5) Mention one advantage of the heap-sort over the merge-sort algorithm and list
their complexities (3 marks)

b) In general, algorithms are classified into paradigms like brute-force, dynamic, greedy,
optimization, and divide & conquer. (total 7 marks: 1 mark each)
1) Determine the paradigm described by each of the following phrases
i) Keep searching for the next optimum solution.
ii) Sub-problems are solved and kept to be reused later.
iii) Examining all possible solutions.
iv) Splitting the problem into parts and solving each.
2) Determine the paradigm of each of the following algorithms
i) Bubble sort algorithm
ii) Binary search algorithm
iii) Dijkstra algorithm.

c) Each of the following phrases describes a particular types of logic, determine it.
1) It is the branch of logic that studies ways of joining and/or modifying entire
statements or sentences to form more complicated ones, as well as the logical
relationships and properties that are derived from these methods of combining or
altering statements.
2) It is known as the first-order logic or quantified logic is a formal language in which
schemes are expressed in terms of variables and quantifiers.
(total 4 marks: 2 mark each)

d) Each of the following phrases describes a particular category of computational


problems like: P, NP, NP-complete, NP-hard problems
1) Problems that can be easily solved by a computer and have a yes/no answer.
2) Problems that are easy to verify, but it would take years to solve it.
Determine the category for each description, and draw a van diagram that describes
the relation between these two categories. (Total 4 marks)

Answer:

2
a) The answers are as follows:
1) The Quick-selection algorithm (1 mark)
2) It is called "Collision", the two techniques are: Probing and chaining. (3
marks)
3) The search complexity is O(n) whatever how the listed is sorted (1 mark)
4) 100 log 64, 100 log n, n log 10, 1000 n, 5 n2, 2n (2 marks)
[Marking note: 2 marks if the whole order is correct, 1 marks if 2 cases are not in
the right places, and 0 mark otherwise]
5) The merge-sort consume much memory than the heap-sort, while they both have O(n
log n) complexity. (3 marks)

b) The algorithm paradigm:


1) The paradigm are as follows:
i) Greedy (1 mark)
ii) Dynamic (1 mark)
iii) Brute force (1 mark)
iv) Divide and conquer (1 marks)

2) The paradigm are as follows:


i) Brute force (1 mark)
ii) Divide-and-Conquer (1 mark)
iii) Greedy (1 mark)
`
c) The type of logic of each one is as follows:
1) Prepositional Logic (2 marks)
2) Predicate logic (2 marks)

d) The category of each description is :


1) P problems (1 mark)
2) NP problems (1 mark)

The van diagram (2 marks)


NP Problems
P Problems

Question 2: (25 marks)

a) For each of the following scenarios choose the “best” data structure that should be
used, and give a rationale for your answer: (10 marks: 1 for the data structure, and 1
for the rationale)
1) Representing the relations between persons on a social network.
2) Demonstrating the chain of command in the military
3) A store is serving the clients based on first in last out.
4) List of items that change repeatedly.

3
5) An application that needs to remember previous commands using the back
button.

b) Given the following array Arr [F, J, C, H, L, A, E, G, I, K, M, D, B], answer the following
set of questions:
1) Draw the heap presentation of this array (1 mark)
2) Find the post-order traversal of this tree. (2 mark)
3) Implement Max-Heapify and show the last presentation (3 mark)

c) Find the complexity of the following algorithms, where A [] and B [] are arrays of size
n. [Note: your answer must show the steps that lead to your final answer]. (9 Marks)
1) for i = 1 to n do
for j = 1 to 10 do
for k = 1 to 10 do
A[k] = i*i + j*j + k*k
k = k*2
end for
end for
end for

2) The algorithm solves the problem of size n by dividing it into 8 subproblems of


size n/8, recursively solving each sub-problem, and then combining the solutions
in constant time. (3 Marks)

3) The algorithm solves the problem by breaking it into 16 sub-problems of 1/4 the
scale, recursively solving each sub-maze, and then combining the solutions in
O(n^4) time. (3 Marks)

Answer:

a) The best data structures are as follows: (10 marks: 1 mark for the data structure, and
1 mark for the rationale) [Note: the rationale can take many forms. In the following
model answer, I just give an example]
1) Graph, because the use of nodes in a graph is similar to people in reality
where the relations between them can be represented through edges
between nodes.
2) Tree, because the chain of command in an army is a hierarchy structure with
different levels of authorities in a pyramid shape. The tree on the other side
afford this structure through root, children nodes, and so on.
3) Queue, because the queue supports the FIFO serving mechanism.
4) Linked-list, because the cost of inserting/deleting a node in a linked list is far
less than its counterpart in other data-structures
5) Stack, because it works using last in-first-out mechanism

e) The Heap problem

4
1) The heap

(1 mark)
2) The post-order traversal: G, I, H, K, M, J, D, B, A, E, C, F (2 mark)
3) Max-Heapify (3 mark)

c) The complexity

1) Time complexity = O(n)*O(1)*O(1) = O(n). (3 Marks)


2) T(n) = 8 T(n/8) + 1, => a = 8, b = 8, d = 0 => a>bd  8 > 80  8 > 1
 T(n)  ( nlog b a) = T(n)  ( nlog 8 8) = T(n)  (n). (3 Marks)
3) T(n) = 16 T(n/4) + O(n^4), => a = 16, b = 4, d = 4 => a<bd  16 < 44  16 <
256  T(n)  ( nd) = T(n)  (n^4). (3 Marks)

Part 2: [50 Marks]


Question 3: (30 Marks)

a) Given the following graph

i) Calculate the minimum cost-spanning


tree using Kruskal’s algorithm. (8 Marks)
[Note: The answer should include the
table of all required information, the
minimum spanning tree and the total
cost of the minimum spanning tree.]
ii) List the right sequence of nodes
traversed by the DFS and BFS
algorithm starting from node A. (6
marks)
iii) Does this graph possess a Euler path or
Euler circuit? why? (4 marks)

5
b) Determine the shortest paths between all pairs
of nodes in the following graph using Floyd-
Warshall algorithm. (12 Marks)

Answer:

a) The given graph:

i) The minimum cost spanning


The answer should include the table of all required information, the minimum
spanning tree and the total cost of the minimum spanning tree.

Edge dv
(A, B) 1 
(A, D) 2 
(B, C) 2 
(D, E) 3 
(E, G) 3 
(B, F) 4 
(A, C) 5 Not Considered
(C, E) 5 Not Considered
(F, G) 6 Not Considered
(C, F) 9 Not Considered

Total cost = ∑ 𝑑𝑣 = 1 + 2 + 2 + 3 + 3 + 4 = 15

ii) The DFS and BFS are as follows:


DFS: A-B-C-E-D-G-F
BFS: A-B-C-D-F-E-G
iii) The Euler path or Euler circuit: there is no Euler path or even circuit (2 marks),
because there exist more than 2 nodes with odd degrees (2 marks)

a) The answer should show all the steps of Floyd-Warshall algorithm.

0 3 ∞
D(0) = [8 0 2 ]
4 9 0

6
0 3 ∞
D(1) = [8 0 2 ]
4 7 0
0 3 5
D(2) = [8 0 2]
4 7 0
0 3 5
D(3) = [6 0 2 ]
4 7 0
Award 3 Marks for each correct matrix in the above matrices

Question 4: (20 Marks)

Given an array of unsorted integers, find the smallest product of all possible pairs in the array.
For example, given arr [19, 5, 16, 12, 5, 3], the smallest product would be 15, which is resulted
from multiplying (5x3).

To solve this problem, consider the following ideas:

i. Study every pair in the given array and return the smallest product.
ii. Sort the array first, and then to get the product of the smallest two integers.

Answer the following questions:

a) Complete the following sentences and explain why: (4 Marks)


i) The complexity of the first idea is …….
ii) The complexity of the first idea is …….

For each of the following sentences, state whether it is true or false and explain
why: (4 Marks)
iii) The second idea will always result in a correct solution
iv) The first idea will always result in a correct solution

b) Design your own idea to solve this problem in better complexity, where n is the
size of the array. (12 marks: algorithm (6 marks), prove of complexity (3 marks),
explain why your solution is better (3 marks))

Answer:

a) Complete the following sentences and explain why: (4 Marks)


i) The complexity of the first idea is O (n2) [The first idea is brute force solution
where all possible pairs are tested resulting in O(n2) complexity.]

7
ii) The complexity of the first idea is O (n log n) [The second solution is to
implement a Sort() function with complexity that could be O(n log n) and
then getting the product of two cells resulting a total complexity O(n log n).]

For each of the following sentences, state whether it is true or false and explain
why: (4 Marks)
iii) The second idea will always results in a correct solution False [because in
case the existence of two negative value as the smallest value in the list,
their product will turn into a big value that does reflect the smallest product]
iv) The first idea will always results in a correct solution True [because all the
possible product will be there and hence finding the smallest product will be
never missed]

b) [total 12 marks: algorithm (6 marks), prove of complexity (3 marks), explain why


your solution is better (3 marks)]

The solution will vary according to the complexity:


For example: a straight forward efficient idea is to get the smallest 2 values in the
array using one for loop with complexity O(n) and then to multiply them, without
the need to sort the whole array.
This solution appears to be efficient, but it does not consider the special case of
having both smallest numbers to be negative and hence their multiplication to be
a big number (not the smallest one).

A solution like this deserves half of the mark = 6 marks, While a solution that consider all
conditions and efficiently handle them would deserve the whole mark = 12 marks.

End of Questions

8
PART 1: ALL QUESTIONS ARE REQUIRED [10 Marks]

Choose the correct answer: (10 marks, 2 marks each)

1) Stack is also called as


a) First in first out
b) First in last out
c) Last in last out
d) Last in first out

2) The complexity of merge sort algorithm is


a) O(n)
b) O(log n)
c) O(n2)
d) O(n log n)

3) To represent hierarchical relationship between elements, which data structure is suitable?


a) Graph
b) Tree
c) Dequeue
d) Priority

4) When determining the efficiency of an algorithm, the space factor is measured by


a) Counting the maximum memory needed by the algorithm
b) Counting the minimum memory needed by the algorithm
c) Counting the average memory needed by the algorithm
d) Counting the maximum disk space needed by the algorithm

5) Linked lists are best suited


a) for relatively permanent collections of data
b) for the size of the structure and the data in the structure are constantly changing
c) for both of above situation
d) for none of above situation

PART 2: ALL QUESTIONS ARE REQUIRED [20 Marks]

Question 1: (10 marks)


a) What is the asymptotic complexity of the following?
i) Finding the smallest element in a stack of size n [2 marks]
ii) Finding the largest element in a linked list of size n [2 marks]
b) Arrange the following complexities in order (best to worst): [3 marks]
O(log n), O(n log n), O(1), O(n), O(n2), O(n2 log n)
c) Which is a less complexity: 100n or 2n2? Justify your answer. [3 marks]

Answer

a) The answer will be as follows:


i) One pop operation is O(1), we need n pop operations, hence the order is O(n) [2 marks]
ii) O(n) [2 marks]

M269 Mock Exam 2/5


b) O(1), O(log n), O(n), O(n log n), O(n2), O(n2 log n) [3 marks]
2
c) 100 n has a lower complexity than 2n , because the rate of increase in the second case is
quadratic while in the first the rate of increase in execution time is linear. We can find a point c
after which all values for the second expression will be larger than all values for the first
expression. [3 marks]

Question 2: (10 marks)

a) Suppose an initially empty queue Q has executed a total of 32 enqueue operations, 10 first
operations, and 15 dequeue operations, 5 of which raised Empty errors that were caught and
ignored. What is the current size of Q? [Hint If a queue is empty when dequeue is called, its size
does not change]. [2 marks]
b) What values are returned during the following series of stack operations, if executed upon an
initially empty stack? push(5), push(3), pop(), push(2), push(8), pop(), pop(), push(9), push(1),
pop(), push(7), push(6), pop(), pop(), push(4), pop(), pop(). [4 marks]
c) What values are returned during the following sequence of queue operations, if executed on an
initially empty queue? enqueue(5), enqueue(3), dequeue(), enqueue(2), enqueue(8), dequeue(),
dequeue(), enqueue(9), enqueue(1), dequeue(), enqueue(7), enqueue(6), dequeue(), dequeue(),
enqueue(4), dequeue(), dequeue(). [4 marks]

Answer

a) The size of the queue is 32−15+5 = 22. [2 marks]


b) The returned value for each execution will be as follows:
push(5)  nothing, push(3)  nothing, pop()  3, push(2)  nothing, push(8)  nothing,
pop() 8, pop() 2, push(9)  nothing, push(1)  nothing, pop() 1, push(7)  nothing,
push(6)  nothing, pop() 6, pop() 7, push(4)  nothing, pop() 4, pop() 9.
[4 marks: 0.5 for each correct output]
c) The returned value for each execution will be as follows:
enqueue(5)  nothing, enqueue(3)  nothing, dequeue() 5, enqueue(2)  nothing,
enqueue(8)  nothing, dequeue() 3, dequeue() 2, enqueue(9)  nothing, enqueue(1) 
nothing, dequeue() 8, enqueue(7)  nothing, enqueue(6)  nothing, dequeue() 9,
dequeue() 1, enqueue(4)  nothing, dequeue() 7, dequeue() 6.
[4 marks: 0.5 for each correct output]

PART 3: ALL QUESTIONS ARE REQUIRED [30 marks]

Question 1: (10 marks)


Consider the following code and answer the below questions

def Xsort( aList ):


for i in range( 1, len( aList ) ):
tmp = aList[i]
k=i
while k > 0 and tmp < aList[k - 1]:
aList[k] = aList[k - 1]
k -= 1
aList[k] = tmp

M269 Mock Exam 3/5


a) What type of sorting algorithm does the Xsort function implement in the above code?
b) Derive the time complexity of this code in the best and worst case.
c) If the array “aList” has the following values: [45, 26, 13, 60, 30], trace down the first two cycles of
this algorithm.

ANSWER: (10 marks)

a) It implements the “insertion-sort” [2 marks]


b) Time Complexity of Solution:
Best case: O(n) [2 marks]
Worst case: O(n2) [2 marks]
c) Start by: 45, 26, 13, 60, 30
1st iteration: 26, 45, 13, 60, 30 [2 marks or zero]
nd
2 iteration: 13, 26, 45, 60, 30 [2 marks or zero]

Question 2: (10 marks)

a) What is the complexity (Big O) of the following pseudo-codes?


[Hint: you should show the steps that lead to your answer]
1) for i  1 to 2n [2 marks]
for j  1 to n
xx+1
2) in [2 marks]
while (i  1)
for j  1 to n
xx+1
i i/ 2
b) Use the master theory to find the O notation of the following recurrence relation: [3 marks]
T(n) = T(n/2) + 1

c) Solve the following linear recurrences and find the complexity: [3 marks]
T(n) = T(n-1) +5 for n > 1 with T(1) = 0

ANSWER: (10 marks)

a) the complexity is as follows:


1) Two loops inside each other of size n  O (n2) [2 marks]
2) Two loops inside each other the first of size n and the second is decrementing in an
exponential behavior  O (n log n) [2 marks]

b) Here a = 1, b = 2, d = 0, a = bd
T(n)  (log(n) )

c) T(n) = 5(n-1) the student has to derive the complexity using any method  (n )

M269 Mock Exam 4/5


Question 3: (10 marks)
Consider the following functions:
a)
def Process (int n):
if (n == 0) do one arithmetic operation
else
for (i = 1; i < n; i++) Process(i)

Find the number T(n) of arithmetic operations done by Process (n) and find the complexity.

b) def Fun (itemType a[ ] , int s , int e , int r)


if ( s == e ) return 0
else
Process (a , s , e , x , y)
d=y-x
return Fun ( a , s+1, e , d )
If the above function is invoked as: p = Fun (a, 1, n, 0) and the function Process() does
2(e - s) arithmetic operations, construct the recurrence relation for the above algorithm, solve
it and then find the exact number of arithmetic operations performed by Fun(), and find the
complexity.

Answer

(Marking guide: 5 marks for each case, 3 marks for solving the linear recurrences and 2 marks for
the complexity)
a) T(n) = ∑n−1
i=1 T(i) = 2T(n − 1) with T(0) = 1, hence T(n) = 2  O(2 )
n n

b) T(n) = T(n-1) + 2(n-1) + 2 = T(n-1) + n for n > 1 with T(1) = 0,


hence T(n) = n2 + n -2  O(n2)

End of Mock Exam

M269 Mock Exam 5/5


Fall Mock Final Exam 17-18

PART 1: ALL QUESTIONS ARE REQUIRED [20 Marks]

Choose the correct answer:

1) Quick sort algorithm is an example of:


a) Greedy approach
b) Improved binary search
c) Dynamic Programming
d) Divide and conquer

2) Two main measures for the efficiency of an algorithm are:


a) Processor and memory
b) Complexity and capacity
c) Time and space
d) Data and space

3) The complexity of Bubble sort algorithm is:


a) O(n)
b) O(log n)
c) O(n2)
d) O(n log n)

4) Finding the location of the element with a given value is:


a) Traversal
b) Search
c) Sort
d) None of above

5) Dijkstra's algorithm is an example of:


a) Greedy algorithms
b) Optimization algorithms
c) Dynamic Programming algorithms
d) Divide and Conquer algorithms

6) Compared to doubly linked lists, in singly-linked lists:


a) Less space is required.
b) Insertion before a node is easier.
c) Traversal in both directions is possible.
d) Both a and b.

7) If there's no base criteria in a recursive program, the program will:


a) Not be executed.
b) Execute until all conditions match.
c) Execute infinitely.
d) Obtain progressive approach.

8) In a graph if e=[u,v], Then u and v are called:


a) End points of e
b) Adjacent nodes
c) Neighbors
d) All of the above

M269 Final Exam 2/7 Fall 2017/2018


9) The time complexity of the following loop is given by:
for (inti = 1; i<= n/2; i++)
{ System.out.println(i*2); }
a) O(n/2)
b) O(logn)
c) O(nlogn)
d) O(n)

10) What is the shortest path from node A to node F?

a) A -> B -> D -> F


b) A -> C -> B -> E -> F
c) A -> F
d) A -> C -> E -> F

PART 2: ALL QUESTIONS ARE REQUIRED [30 Marks]

Question 1: (10 marks)

For each of the following scenarios choose the “best” data structure that should be used:

a) Suppose that a grocery store decided that customers who come first will be served first.
b) A list must be maintained so that any element can be accessed randomly.
c) A program needs to remember operations it performed in opposite order.
d) Representing the relation between family members.
e) The size of a file is unknown. The entries need to be entered as they come in. Entries must be
deleted when they are no longer needed. It is important that structure has flexible memory
management.

Answer: (10 marks, 2 marks each)

a) Queue
b) Array or List
c) Stack

M269 Final Exam 3/7 Fall 2017/2018


d) Tree
e) Linkedlist

Question 2:(8 marks)


Given the following code that describes the naive_pattern_matching:

def naive_pattern_matching(pattern, st):


n = len(st);
m = len(pattern);
match_set = [];
for i in range(0, n-m):
for j in range(0, m):
if pattern[j] != st[i+j]:
break;
if j == m-1:
match_set.append(i);
return match_set;

a) How many times will the inner loop be executed? (2 marks)


b) The complexity of naive pattern matching algorithm is O(m*n) or O(m/n) or O(m+n) or O(m n)?
(2 marks)
c) Describe the main idea of the naive pattern matching algorithm? (2 marks)
d) Describe briefly the disadvantages of the naive pattern matching algorithm? (2 marks)

Answer: (8 marks, 2 marks each)


a) The inner for loop will be executed n-m times.
b) O(m*n).
c) The main idea of the naive pattern matching algorithm is to match the pattern with each part of
the same length in the string to be searched in by shifting to the right.
d) The main disadvantage of the naive pattern matching algorithm is that it matches the pattern
with the whole string and shift one character to the right so it consumes a lot of time to find the
pattern.

Question 3:(12 marks)

a) Differentiate between the P and NP types of problems, then give an example for each one of
them
b) Differentiate between computational thinking and computational problem?
c) Discuss the difference between finite state machine model and logic programming?

Answer: (12 marks, 4 marks each)


a) P problems are problems that have a yes/no answer and can be easily solved by a computer.
For example, determining whether a number is prime or not.
NP problems are problems that have yes/no answers that are easy to verify, but are hard to
solve in the sense that it would take years, decades or centuries for your computer to come up
with an answer. For example, the travelling salesman problem is trying to figure out the
shortest trip through a bunch of cities, visiting each city only once.

M269 Final Exam 4/7 Fall 2017/2018


b) Computational thinking as not merely knowing how to use an algorithm or a data structure,
but, when faced with a problem, to be able to analyze it with the techniques and skills that
computer science puts at our disposal.
Computational problem is described as a problem that is expressed sufficiently precisely that
it is possible to attempt to build an algorithm to solve it.
c) FSM is a mathematical model of computation that can be in exactly one of a finite number
of states at any given time. The FSM can change from one state to another in response to some
external inputs; the change from one state to another is called a transition.
Logic programming is a type of programming which is largely based on formal logic. Any
program written in a logic programming language is a set of sentences in logical form,
expressing facts and rules about some problem domain.

PART 3: ALL QUESTIONS ARE REQUIRED [50 marks]

Question 1:(15 marks)

Using the Kruskal algorithm:


a) Explain briefly the purpose and the type of this algorithm (4 marks)
b) Describe the algorithm in three steps (6 marks)
c) Draw the minimum spanning tree of the following graph and specify its cost (5 marks)

Answer

a) Type: Kruskal's algorithm is a greedy algorithm (2 marks)


Purpose: it finds a minimum spanning tree for a connected weighted graph. It finds a
subset of the edges that forms a tree that includes every vertex, where the total weight
of all the edges in the tree is minimized. (2 marks)

b) The steps: (6 marks, 2 marks for each step)


[marking note: many descriptions for the algorithm can accepted, however, it should be
around the following steps]

1. Arrange the edges by weight: least weight first and heaviest last.
2. Choose the lightest not examined edge from the diagram. Add this chosen edge to
the tree, only if doing so will not make a cycle.
3. Stop the process whenever n - 1 edges have been added to the tree

M269 Final Exam 5/7 Fall 2017/2018


c) the minimum spanning tree, the cost is 13 (1 mark)

(4 marks)

Question 2: (15 marks)

Considering the above graph, use the Dijkstra’s algorithm to find the shortest path from node
A to node F. To answer this question, you have to:
a. Fill out the following table showing the intermediate distance values iteratively through all
the vertices starting from node A till the node F is reached.
b. Draw the final path and calculate its cost. (5 marks)

iteration Initial 1 2 3 4 5
A 0 -- -- -- -- --
B ∞ 1 … … … …
C ∞ 2 … … … …
D ∞ 4 … … … …
E ∞ ∞ … … … …
F ∞ ∞ … … … …
Answer
a)
iteration Initial 1 2 3 4 5
A 0 -- -- -- -- --
B ∞ 1
C ∞ 2 2
D ∞ 4 4 4 3
E ∞ ∞ 2 2
F ∞ ∞ ∞ ∞ 9 5
[Total 10 marks: 2 marks for each correct value in the circles]

M269 Final Exam 6/7 Fall 2017/2018


b)

The path is A-B-E-D-F and the cost is 1+1+1+2 = 5


[Total 5 marks: 3 mark for the path and 2 mark for the cost]
Question 3:(10 marks)

Fill the table below with the big-O notation and the order (which is a number from 1 to 5, where 1
represents the asymptotically smallest and 5 represents the asymptotically largest):

Expression Big-O Order


4n2 log n O(n2logn) 5
n log n O(n log n) 3
10n O(n) 2
2
3n2/50+8n O(n ) 4
700 O(1) 1
(10 marks, 1 mark for each field)
Question 4: (10 marks)

1. Use Master Theorem to find the O notation for the following recurrence relations.
a. T(n) = 4T(n/2) + n (5 marks)
2
b. T(n) = 4T(n/2) + n (5 marks)
Answer:
[marking note: the solution passes through 3 steps:
1) finding a, b, and d (1.5 marks)
2) check the correct condition (1.5 mark)
3) find the Big O correctly (2 marks) ]

a. T(n) = 4T(n/2) + n
a = 4, b = 2, d=1 . a = 4 > bd = 21=2
Case 3: f (n) = nlog a=nlog4=n2
 T(n) = O(n2).
b. T(n) = 4T(n/2) + n2
a = 4, b = 2, d=2 . a = 4 = bd = 22=4
Case 2: f (n) = nd log n
 T(n) = O(n2 log n).
End of the Final Exam

M269 Final Exam 7/7 Fall 2017/2018


Scan or Click me.

You might also like