CS2040 1920SEM1 Midterm Sample Ans
CS2040 1920SEM1 Midterm Sample Ans
SCHOOL OF COMPUTING
Midterm (20%)
AY2019/20 Semester 1
INSTRUCTIONS TO CANDIDATES
1. Do NOT open the question paper until you are told to do so.
2. This question paper contains TWO (2) sections with sub-questions. Each section has a
different length and different number of sub-questions. It comprises Thirteen (13) printed
pages, including this page.
3. Answer all questions in this paper itself. You can use either pen or pencil. Write legibly!
4. This is an Open Book Quiz. You can check the lecture notes, tutorial files, problem set files,
CP3 book, or any other books that you think will be useful. But remember that the more
time that you spend flipping through your files implies that you have less time to actually
answer the questions.
5. When this Quiz starts, please immediately write your Matriculation Number and Tutorial
Group (if you don’t know your tutorial group, write your TA name and time slot).
A
STUDENT NUMBER:
Total 100
- 1 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
Answer: false
For any n > 1, 1st call to recursion1 will go into else clause where the for loop will iterate
n times. Each iteration calls recursion2 and for any i > 1 recursion2 immediately returns
(base case), otherwise it calls recursion1 again however this call to recursion1 will now
immediately return since i <= 1. Thus recursion2 will at most take O(1) time regardless
of value passed in. So in total the time taken is simply O(N) due to the for loop.
2. Given the same input, insertion sort will always have time complexity equal to or worse
than mergesort. [true/false]
Answer: false
If input of size N given is already sorted, insert sort will only take O(N) time since or each
iteration of the outer for loop, the inner for loop for insertion sort will only execute once
and determine that value at current index i is already in its correct position.
However for mergesort regardless of whether input is sorted or not it will still take
O(NlogN) time.
- 2 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
3. If we implement a queue ADT using a circular linked list, only the time complexity for
either enqueue or dequeue operation is 𝑂𝑂(1) time but not both. [true/false]
Answer: false
If we maintain a tail reference, then enqueue which is equivalent to inserting to the tail
of the circular linked list can be done in O(1) time as follows
newNode.next = tail.next
tail.next = newNode
tail = tail.next
dequeue which is equivalent to remove from the head of the circular linked list can also
be done in O(1) time as follows
tail.next = tail.next.next;
4. Given 2 arrays of size 𝑁𝑁 each that contains unsorted integers that have values between
0 and 2𝑁𝑁 , we can check whether they contain the same elements in 𝑂𝑂(𝑁𝑁) time by first
performing radix sort on both in 𝑂𝑂(𝑁𝑁) time then simply go from index 0 to 𝑁𝑁-1 to check
if the value at the current index in both array is the same or not. [true/false]
Answer: false
Radix sort is 𝑂𝑂(𝑑𝑑𝑑𝑑) or more precisely 𝑂𝑂(𝑑𝑑(𝑁𝑁 + 𝑏𝑏)) where 𝑏𝑏 is the number of
buckets/queues and 𝑑𝑑 is the number of digits in the integers to be sorted. In this case
the integers can be up to 2𝑁𝑁 , so the number of digits is 𝑂𝑂(𝑁𝑁) and not bounded by a
constant. Thus it will take 𝑂𝑂(𝑁𝑁 2 ) instead of 𝑂𝑂(𝑁𝑁).
Even in the event where we convert the integers into a base N number and use N buckets
instead and not count the time to do the conversion, there will still be 𝑂𝑂(𝑁𝑁/𝑙𝑙𝑙𝑙𝑙𝑙)
number of digits per base 𝑁𝑁 number and so Radix sort is still 𝑂𝑂(𝑁𝑁 2 /𝑙𝑙𝑙𝑙𝑙𝑙) and not 𝑂𝑂(𝑁𝑁).
- 3 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
a) After taking CS2040 for half a semester, you have decided to put what you’ve learned to
good use and simulate a rudimentary text editor. To make it simple you only capture input
from the keys ‘0’ to ‘9’, ‘a’ to ‘z’, ‘A’ to ‘Z’, the space key ‘ ’, the enter key ‘\n’ and the
backspace key which is captured as ‘\b’. These inputs are then stored as a string. Given
such a length 𝑁𝑁 input string 𝑨𝑨, give an algorithm and the associated data structure to
display the final text in 𝑂𝑂(𝑁𝑁) time. [18 marks]
- 4 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
b) After you tried out your simulator, you discovered that somehow the backspace key press
has a problem and instead of a backspace it will randomly be replaced by a home key or
end key. Going with the error, you now want to change your algorithm and associated
data structure so that it will output the final text with the inclusion of these random home
and end keys and the exclusion of the backspace key. You can assume home key is ‘\H’
and end key is ‘\E’. Your algorithm should still run in 𝑂𝑂(𝑁𝑁) time. [12 marks]
- 5 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
a.) Given an array 𝐴𝐴 of 𝑁𝑁 (𝑁𝑁 > 1) integer values indicating the volume of 𝑁𝑁 bottles to be placed
on the conveyer belt from index 0 to index 𝑁𝑁 − 1 in that order, and 𝐻𝐻 the number of seconds,
give the algorithm and associated data structure that will compute the number of bottles that
are completely full after 𝐻𝐻 seconds. [18 marks]
E.g1: Given 𝐴𝐴 = [1,3,7,1,4] and 𝐻𝐻 = 190, the number of full bottles is 3 after 190 seconds.
E.g2: Given 𝐴𝐴 = [1,3,1,4,7] and 𝐻𝐻 = 190, the number of full bottles is 4 after 190 seconds.
Answer:
Simulate the process using a queue!
1.) Let Q be a queue, fbcount = 0, H’ = H
2.) For i from 0 to N-1
Q.enqueue(A[i])
3.) while (H’ > 0 && !Q.empty())
If (H’ < H)
H’ = H’-10
let cur = Q.poll()
H’ = H’-min(30, cur*10)
cur = cur-3
if (cur > 0 and H’ > 0)
Q.enqueue(cur)
else if (cur < 0 && H’ >= 0)
fbcount = fbcount+1
4.) Print out fbcount
- 6 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
This facility is a single floor rectangular structure of width 100 meters with strangely no roof
and running along the 2 sides of the facility length-wise are walls of 𝑴𝑴 + 𝟏𝟏 meters high each
where 𝑴𝑴 is an integer. Along the length of the 2 side walls, 𝑵𝑵 walls of integer heights ranging
from 3 meters to 𝑴𝑴 meters are placed at intervals of 10 meters perpendicular to the side
walls to create rooms and since the pipes run through all the rooms, they all start filling with
the poisonous liquid. Once the liquid in a room reaches over the height of either of its room
walls, it will overflow into the adjoining room and so on, until it flows into the moat. You can
assume the moat can contain and neutralize an infinite amount of the liquid. Your task is to
now calculate what is the maximum volume of liquid contained within the facility. For
simplicity sake assume walls are 0 meters thick and ignore all the equipment in the facility.
When the facility contains the maximum volume of liquid, the liquid will fill the facility such
that for all pairs of walls 𝑊𝑊 and 𝑊𝑊’ (assuming without loss of generality that 𝑊𝑊 is to the left
of 𝑊𝑊’) of height ℎ and ℎ’ respectively such that
1. there are no walls taller than min(ℎ, ℎ′ ) between 𝑊𝑊 and 𝑊𝑊’
2. If ℎ ≤ ℎ′ (𝑊𝑊 is the shorter wall), there are no walls taller than ℎ to the left of 𝑊𝑊
3. If ℎ′ ≤ ℎ (𝑊𝑊’ is the shorter wall), there are no walls taller than ℎ′ to the right of 𝑊𝑊′
then all rooms between 𝑊𝑊 and 𝑊𝑊′ will be submerged up to height min(ℎ, ℎ′ ).
The input given to you is an array 𝑨𝑨 of the height of the walls separating the rooms starting
from the 1st wall to the 𝑁𝑁 𝑡𝑡ℎ wall.
100m width
6th wall
Walls separating
rooms at 10m
1st wall
The 2 side walls are height 𝑀𝑀+1 each while the 6 walls have integer height ranging from 3 to 𝑀𝑀.
- 7 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
13m
11m
7m 8m
6m 6m
The heights of the walls from the 1st to the 6th is 11,13,7,6,8,6 meters respectively.
In the example above, the maximum volume of poisonous liquid contained in the facility can
be shown below based on how the liquid submerges the rooms.
13m
11m
7m 8m
6m 6m
(11*10*100)+(8*30*100)+(6*10*100) = 41,000 m3
Any excess liquid will simply flow into the moat (since there is no roof).
11m 10m
8m
6m 5m
4m
the maximum volume of poisonous liquid contained in the facility can be shown as follows
11m 10m
8m
6m 5m
4m
10*10*100+8*10*100+6*10*100+5*10*100+4*10*100 = 33,000 m3
- 8 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
b) Given input array 𝑨𝑨 of the height of the 𝑁𝑁 walls from 1st wall to 𝑁𝑁 𝑡𝑡ℎ wall, come up with
an algorithm and appropriate data structure so that the maximum volume of poisonous
liquid that can be contained in the facility can be computed in 𝑂𝑂(𝑁𝑁) time. [12 marks]
1.) Let S be a stack that store integers pairs <X,Y> where X represents the height of a wall,
and Y represents how many rooms are submerged to a height of X to the left of the
wall. S will contain walls in order of decreasing height from bottom to top of stack.
2.) Let maxVol be the maximum volume of poisonous liquid contained in the facility and
is initialized to 0
4.) while (!S.empty()) // pop all remaining items in S and add to maxVol
maxVol += S.peek().X*S.pop().Y*10*100
Each wall is at most pushed into the stack once and removed from the stack once. Thus
there are at most O(N) push and pop operations which costs O(1) each. So total time taken
is O(N).
First, let’s assume that the heights of all walls are distinct. We will handle the case
where not all heights are distinct later. We make the following claim:
Claim 1
Consider any pool of liquid surrounded by two walls on its left and right. Let the heights of the
two walls be A[i] and A[j] respectively. Then, one of the following must hold:
● A[i] < A[j] (the wall on the right is taller than the wall on the left)
● A[i] > A[j] (the wall on the left is taller than the wall on the right)
- 9 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
Since one of the above conditions must hold for each wall, we can first find all pools that
satisfy the first condition, and then find all pools satisfying the second condition. Then, we
would have found all the pools that can possibly be formed.
To find all pools satisfying the first condition, we can first start from the leftmost wall, and
consider that to be the left wall enclosing the first pool. Then, we iterate from left to right
to find the next wall higher than the first wall to be the right wall enclosing the first pool.
Then, we can let this wall be the left wall enclosing the second pool, and we repeat this
process.
To find all pools satisfying the second condition, we use a similar procedure. Start from the
rightmost wall and consider that to be the right wall enclosing the first pool. Then, iterate
from right to left to find the next wall higher than the first wall to be the left wall enclosing
the first pool. Then, let this wall be the right wall enclosing the second pool, and repeat this
process.
Algorithm 1: Computes total volume of all pools, assuming that heights of walls are distinct
print total_volume
This algorithm works if the heights of all walls are distinct. However, in the question, the
heights of all walls may not necessarily be distinct. So, in the question, our conditions
actually look like this:
Claim 2
Consider any “pool” of liquid surrounded by two walls on its left and right. Let the heights of
the two walls be A[i] and A[j] respectively. Then, at least one of the following must hold:
● A[i] ≤ A[j] (the wall on the right is at least as tall as the wall on the left)
● A[i] ≥ A[j] (the wall on the left is at least as tall as the wall on the right)
- 10 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
Notice that now, some pools actually satisfy both conditions instead of just one condition: the pools
surrounded by two walls with the same height on both sides. So, Algorithm 1 may double count
some pools, and we may get an incorrect total volume.
But exactly which pools are actually double counted? We make another observation:
Claim 3
Let H be the maximum height over all walls. All pools where both walls surrounding the pool are of
height H will be double counted.
So, we can modify the algorithm to ignore all pools where both walls surrounding the pool
are of height H in the second loop above, when iterating through the walls from right to left.
The modified pseudocode is shown below (modifications to Algorithm 1 shown in blue):
Algorithm 2: (Solution for 6b.) Computes total volume of all pools
- 11 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
a) Company W houses some of the most advanced military weapons in the world. Each floor
of the company is laid out in an 𝑁𝑁 by 𝑀𝑀 grid (𝑁𝑁 is the # of rows and 𝑀𝑀 is the # of columns),
where the top left cell is at row 0, column 0, i.e (0,0) and the bottom right cell is at row
𝑁𝑁 − 1 and column 𝑀𝑀 − 1, i.e (𝑁𝑁 − 1,𝑀𝑀 − 1). In order to protect their assets, 𝐾𝐾 (𝑘𝑘 ≤
min(𝑀𝑀, 𝑁𝑁) number of laser defenses are installed on every floor. Each laser defenses’
position is given by its row and column coordinate on the grid. Now a laser defense at
coordinate (X,Y) will have a laser barrier shooting out all the way along both row X and
column Y. Due to this feature of the laser defense, the following non-conflict property
must hold:
No laser defense can be placed on the same row or column as another laser defense
otherwise their laser barrier will destroy each other.
E.g: Given the 2 following grid and laser defenses, Fig 1 is an invalid configuration while
Fig 2 is a valid configuration.
(1,0)
(1,0) (1,2)
(2,1)
(3,1)
(4,3)
(4,3)
Fig1: 5x4 grid, with laser Fig2: 6x4 grid, with laser
defenses as indicated defenses as indicated
by their coordinates. by their coordinates.
Lasers at (1,0) & (1,2) No lasers violate the
violates the non-conflict non-conflict property
property here.
You may assume there is a coordinate class with attributes 𝑥𝑥 and 𝑦𝑦 representing the row
and column index respectively.
Now given 𝑁𝑁, 𝑀𝑀, 𝐾𝐾 and an array 𝐴𝐴 of 𝐾𝐾 coordinates representing the position of the 𝐾𝐾
lasers, give an algorithm for the method Valid(𝑵𝑵, 𝑴𝑴, 𝑲𝑲, 𝑨𝑨) that returns true if the 𝐾𝐾 lasers
are placed in a non-conflicting configuration otherwise return false. Valid(𝑵𝑵, 𝑴𝑴, 𝑲𝑲, 𝑨𝑨)
must run in 𝑂𝑂(𝐾𝐾) time. [10 marks]
- 12 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
Answer:
Non-conflict property means no row value and column value can be repeated for the set
of laser defense positions.
boolean Valid(N,M,K,A)
1.) Let H and H’ be two hash sets. H stores row values and H’ stores column values
2.) For all coordinates (X,Y) in A
if (H.get(X) == null)
H.put(X)
else
return false
if (H’.get(Y) == null)
H’.put(Y)
else
return false
3.) return true
- 13 of 14 -
CS2040 Midterm (AY2019/20 Semester 1)
Now given 𝑁𝑁, 𝑀𝑀, 𝐾𝐾, 𝐴𝐴 as before and the coordinates 𝑃𝑃 of an intruder, give the best
algorithm you can think of for the method SmallestArea(𝑵𝑵, 𝑴𝑴, 𝑲𝑲, 𝑨𝑨, 𝑷𝑷) which will return
the area of the activated rectangular laser configuration that will trap the intruder. If
there is no laser configuration that can trap the intruder return -1. Analysis the time
complexity of your algorithm. [18 marks]
Answer:
O(K^2) time algorithm:
Key idea: For lasers in a rectangular configuration, if we have 2 of the laser positions that
are in a diagonal, we can immediately get the positions of the 2 other lasers in the other
diagonal.
SmallestArea(N,M,K,A,P)
== END OF PAPER ==
- 14 of 14 -