MS Topic 5 Study Pack Jan 2024
MS Topic 5 Study Pack Jan 2024
1. 23M.1.HL.TZ1.2
[2]
Markscheme
Award [2 max]
print queue (serving requests on a shared printer) / spooling in printer;
CPU task scheduling;
handling of interrupts (in the same order as they arrive);
buffer for devices like keyboard;
queues in routers/ switches;
mail queues;
simulation/ computer modelling of physical queues (e.g., a customer waiting line
in
a supermarket queue, a call centre where technical personnel take calls and
provide service, etc.);
handling website traffic/ network congestion;
maintaining playlist in media player; Note: Accept other appropriate examples of
applications of queues in computing.
Examiners report
Most candidates were able to identify two applications of queues in computing.
2. 23M.1.HL.TZ1.8
Consider the following binary tree, in which each node stores a value greater than all the values
in the node’s left subtree and less than those in its right subtree.
Markscheme
Award [1 max] A C E G;
Examiners report
It is evident that some candidates do not know the meaning of the term 'leaf
node'.
[1]
Markscheme
Award [1 max] A C B E G F D;
Examiners report
A well answered question.
(c) Sketch the resulting binary tree after the deletion of the root node.
[3]
Markscheme
Award [3 max]
Award [1] for the correct root
Award [1] for the correct left subtree
Award [1] for the correct right sub-tree.
OR
Examiners report
Some candidates did not delete the root node.
3. 23M.1.HL.TZ1.13
rec(A)
if A >= 2
then
return rec(A-2) + rec(A-1)
else
return 1
end if
end rec
[4]
Markscheme
Award [4 max]
The working may be differently represented. If only the final result (8) is shown,
then award only one mark. rec(5)
= rec(3) + rec(4) ;
= rec(1) + rec(2) + rec(2) + rec(3) ;
= 1 + rec(0) + rec(1) + rec(0) + rec(1) + rec(1) + rec(2) ;
= 1 + 1 + 1 + 1 +1 + 1 + rec(0) + rec(1) = 8 ;
Examiners report
Most candidates achieved some marks for this question, full marks were not rare.
(b) Outline two disadvantages of recursive methods.
[4]
Markscheme
Award [4 max]
Award [1] for a disadvantage and [1] for the elaboration, ×2. recursion is memory
intensive;
because memory (call stack) is used to store all the intermediate arguments and
return values/ could lead to stack overflow (if there is a large amount of data);
recursion can be slow;
if not implemented correctly/if too many recursive calls occur; difficult to think of
the logic of a recursive function/ complexity of the paradigm;
hard to construct/ analyse /understand the code;
Examiners report
Was reasonably well answered with many gaining at least two of the marking
points.
[2]
Markscheme
Award [2 max]
isEmpty() returns a Boolean value True if the stack size is 0, else it returns False/
checks if stack is empty or not;
it is used/called in conditions in if/while statements/ it is called before an attempt
is made to remove the value from the stack;
to prevent performing operations on an empty stack/ to prevent stack underflow
error;
Examiners report
Most candidates outlined well the purpose of the stack access method isEmpty()
The stack TOWNS holds several town names, and the name “Cardiff” is on the top of the
TOWNS stack (see Figure 1a).
An algorithm is needed that will reverse the contents of the TOWNS stack. The name “Geneva”
should be on top of the TOWNS stack after reversing its contents (see Figure 1b).
You must use stack access methods and queue access methods in your response.
[5]
Markscheme
Award [5 max]
Award [1] for correct use of the stack and queue access methods (isEmpty(),
push(), pop(),enqueue(), dequeue())
Award [1] for loop through the TOWNS stack
Award [1] for taking an element from the top of the TOWNS stack
Award [1] for enqueuing the value popped from the TOWNS stack to the TEMP
queue
Award [1] for loop through the TEMP queue
Award [1] for pushing the value dequeued from the TEMP queue onto the
TOWNS stac Example:
loop while not TOWNS.isEmpty()
X=TOWNS.pop()
TEMP.enqueue(X) //TEMP is an empty queue
end while
loop while not TEMP.isEmpty()
Y=TEMP.dequeue() //instead of these 2 statements
TOWNS.push(Y) //TOWNS.push(TEMP.dequeue())
//can be written
end while
Examiners report
There were excellent responses to this question. Most candidates achieved some
marks for the algorithm. However, some candidates did not score any marks for
Part (d).
4. 23M.1.HL.TZ2.2
[2]
Markscheme
Award [2 max]
print queue (serving requests on a shared printer) / spooling in printer;
CPU task scheduling;
handling of interrupts (in the same order as they arrive);
buffer for devices like keyboard;
queues in routers/ switches;
mail queues;
simulation/ computer modelling of physical queues (e.g., a customer waiting line
in
a supermarket queue, a call centre where technical personnel take calls and
provide service, etc.);
handling website traffic/ network congestion;
maintaining playlist in media player; Note: Accept other appropriate examples of
applications of queues in computing.
Examiners report
Most candidates were able to identify two applications of queues in computing.
5. 23M.1.HL.TZ2.8
Consider the following binary tree, in which each node stores a number greater than all the
numbers in the node’s left subtree and less than those in its right subtree.
(a) Identify the leaf nodes in this binary tree.
[1]
Markscheme
Award [1 max] 4 7 9;
Examiners report
It is evident that some candidates do not know the meaning of the term 'leaf
node'.
[1]
Markscheme
Award [1 max] 6 3 5 4 8 7 9;
Examiners report
A well answered question.
(c) Sketch the resulting binary tree after the deletion of the root node.
[3]
Markscheme
Award [3 max]
Award [1] for the correct root
Award [1] for the correct left subtree
Award [1] for the correct right sub-tree.
OR
Examiners report
Some candidates did not delete the root node.
6. 23M.1.HL.TZ2.14
Three dice are thrown, with faces that have numbers from 1 to 6.
The dice are thrown seven times, and the data are stored in a two-dimensional array called
DICEDIAL (see Figure 2).
(a) Construct an algorithm in pseudocode to calculate the sum of all values stored in
the DICEDIAL array.
[3]
Markscheme
Award [3 max]
Award [1] for a correct row loop
Award [1] for a correct column loop
Award [1] for initializing SUM and summing inside the loop using correct array
indexes Example 1:
SUM=0
loop I from 0 to 6
//accept DICEDIAL.length-1
// or len(DICEDIAL)-1 instead of 6
loop J from 0 to 2
//accept DICEDIAL[I].length-1
// or len(DICEDIAL[I])-1 instead of 2
SUM = SUM + DICEDIAL[I][J]
end loop
end loop Example 2:
I =0
SUM=0
loop while I <= 6
j=0
loop while J <= 2
SUM =SUM + DICEDIAL[I][J]
J=J+1
end loop
I=I+1
end loop
Examiners report
Responses to question 14 ranged from poor to excellent. Many candidates
constructed excellent algorithms. However, constructing algorithms proved difficult
for some candidates. They made some common errors while using arrays and
loops, such as overlooking boundaries, two-dimensional array was not indexed by
two subscripts - one for the row and one for the column, initializing the highest
row total incorrectly, outputting the highest total many times, etc.
The DuplicateNum() sub-program will produce the following from the values used in Figure 2:
DuplicateNum(DICEDIAL,0) returns 2
DuplicateNum(DICEDIAL,2) returns 0
[4]
Markscheme
Award [4 max] Example 1 (if-else statement):
Award [1] for initializing VAL to 0 and return VAL / return 0 (in case no duplicates)
Award [3 max] for determining a correct value (1 mark for each correct condition
and change of the value of VAL if needed) Note: Award marks for determining a
correct return value in each of possible cases: three different values in row R- no
duplicates, any two numbers/values in row R are the same and all three values in
row R are the same. Award [1] for correct use of row index and column index in
the DICEDIAL array Note: the method heading may not appear in a candidate’s
response. DuplicateNum (DICEDIAL, R)
VAL=0 if DICEDIAL[R][0] = DICEDIAL[R][1]
then
VAL= DICEDIAL[R][0] // or VAL= DICEDIAL[R][1]
else
if DICEDIAL[R][0] = DICEDIAL[R][2]
then
VAL= DICEDIAL[R][0]
else
if DICEDIAL[R][1] = DICEDIAL[R][2]
then
VAL= DICEDIAL[R][1]
end if
end if
end if
return VAL
end DuplicateNum Example 2 (several if statements- inefficient, but it outputs
a correct value):
Award [1] for each correct if statement, ×4
Award [1] for correct use of row index and column index in the DICEDIAL array
if //three different numbers
DICEDIAL[R][0]!=DICEDIAL[R][1]
and DICEDIAL[R][0]!=DICEDIAL[R][2]
and DICEDIAL[R][1]!=DICEDIAL[R][2]
then
RESULT=0
end if
if DICEDIAL[R][0]=DICEDIAL[R][1] and DICEDIAL[R][0]=DICEDIAL[R][2]
then //three same numbers
RESULT = DICEDIAL[R][0]
end if
//any two same
if DICEDIAL[R][0]=DICEDIAL[R][1] or DICEDIAL[R][0]=DICEDIAL[R][2]
then
RESULT = DICEDIAL[R][0]
end if
if DICEDIAL[R][1]=DICEDIAL[R][2]
then
RESULT = DICEDIAL[R][1]
end if
return RESULT
Note: Accept answers written in Java/ Python. The following example answer is
written in Java.
public int DuplicateNum (int[][] DiceDial, int row)
{
if(DiceDial[row][0] == DiceDial[row][1] || DiceDial[row][0] ==
DiceDial[row][2])
{
return DiceDial[row][0];
}
else if(DiceDial[row][1] == DiceDial[row][2])
{
return DiceDial[row][1];
}
else return 0;
}
The sub-program highestRT(DICEDIAL) accepts the DICEDIAL array and outputs the highest
row total and the indexes of all the rows with that total.
From the example data given in Figure 2, highestRT(DICEDIAL) would output that the highest
row total is 16, and it occurs in the rows with indexes 3 and 4.
[8]
Markscheme
Award [8 max] Example 1:
Award [1] for initializing HIGHEST
Award [1] for correct row loop (I)
Award [1] for calculating the sum of all elements in the Ith row
Award [1] for using correct indexes in the DICEDIAL array
Award [1] for comparing the row sum with the highest row sum so far
Award [1] for and changing the value of HIGHEST if needed
Award [1] for outputting the highest row sum once
Award [1] for the second loop
Award [1] for comparing the row total with the highest row total
Award [1] for outputting row numbers (rows with the highest total) Note: The
method heading may not appear in candidates’ responses. highestRT(DICEDIAL)
HIGHEST = 0 // any number <= 0 OR the first-row total loop I from 0 to 6
SUM = DICEDIAL[I][0] + DICEDIAL[I][1] + DICEDIAL[I][2]
//inner loop may be used instead of this statement
//(see Example 2)- to calculate SUM of values in row I if SUM > HIGHEST
// or >= then HIGHEST = SUM
end if
end loop output(‘the highest row total:’, HIGHEST)
output(‘the highest row total occurs in the following rows:’) loop I from 0 to 6
SUM = DICEDIAL[I][0] + DICEDIAL[I][1] + DICEDIAL[I][2] if SUM =
HIGHEST then output (I)
end if
end loop
end highestRT Example 2:
Award [2 max] for defining the ROWTOTALS array (1 mark for correct row loop
(I) and 1 mark for calculating the sum of all elements in the Ith row of the
DICEDIAL array)
Award [1] for initializing HIGHEST
Award [3 max] for searching for the highest (1 mark for the correct loop, 1 mark
for comparing the row sum with the highest row sum so far and 1 mark for and
changing the value of HIGHEST if needed)
Award [1] for outputting the highest row sum once
Award [3 max] outputting the numbers of rows with the highest total (1 mark for a
loop, 1 mark for comparing the row total with the highest total and 1 mark for
outputting the corresponding index in the ROWTOTALS array) loop I from 0 to 6
S=0
loop K from 0 to 2 S = S + DICEDIAL[I][K]
end loop
ROWTOTALS[I] = S
end loop
//ROWTOTALS[R] holds the sum of all
//numbers in row R of the DICEDIAL array HIGHEST = 0 //any number <= 0
OR ROWTOTALS[0] loop I from 0 to 6
if ROWTOTALS[I] > HIGHEST then HIGHEST = ROWTOTALS[I]
end if
end loop //searching for the highest row total output(‘the highest row total:’,
HIGHEST) output(‘the highest row total occurs in the following rows:’) loop I from
0 to 6 if ROWTOTALS[I] = HIGHEST then output(I)
end if
end loop Example 3:
Award [1] for initializing MAXT
Award [1] for correct row loop (R)
Award [1] for calculating the sum of all elements in row R (using correct indexes
in the DICEDIAL array)
Award [1] for comparing the row sum with the highest row sum so far (S ==
MAXT), and changing
the value FLAGMAXTIND[R] to 1 if they are equal
Award [1] for comparing the row sum with the highest row sum so far (S > MAXT)
and updating the highest row sum so far
Award [1] for reinitializing FLAGMAXTIND array
Award [1] for changing the value FLAGMAXTIND[R] to 1
Award [1] for outputting the highest row total only once
Award [2] for outputting row numbers with the highest total (1 mark for a loop, 1
mark for output within if statement)
// assume FLAGMAXTIND - zero array initialized
MAXT = 0
loop R from 0 to 6
S = DICEDIAL[R][0]+ DICEDIAL[R][1]+ DICEDIAL[R][2]
if S = MAXT
then
FLAGMAXTIND[R]=1
end if
if S > MAXT
then
MAXT = S
loop K from 0 to 6
FLAGMAXTIND[K]=0
end loop
FLAGMAXTIND[R]=1
end if
end loop output('The highest row total is', MAXT) output(' and it occurs in the
following rows:')
loop R from 0 to 6
if FLAGMAXTIND[R] == 1 // or FLAGMAXTIND[R] != 0
then
output(R)
end if
end loop
7. 22N.1.HL.TZ0.8
A computer science student is coding and running a program while several documents, such as
essays, lab reports and homework, are being printed out.
[1]
Markscheme
Award [1] max.
A data structure in which items are added to the tail/rear (one end) and removed
from the head/front (another end) / first in first out (FIFO) data structure;
Examiners report
A well answered question.
(b) Identify two different queues that are used in this scenario.
[2]
Markscheme
Award [2] max.
Print queue;
Keyboard queue;
Accept any other job queue (program is running!);
Examiners report
A well answered question.
8. 22N.1.HL.TZ0.13
A list of students’ names and test scores are written in a teacher’s notebook in alphabetical
order. The teacher uses an application that allows her to input all of the names and scores in the
order they appear in her notebook. The application orders the scores from highest to lowest and
then outputs all the names and scores (see Figure 1).
The application:
• stores the input data in two arrays: NAMES and SCORES (see Figure 2)
• sorts the input data in order of scores from the highest to the lowest by using a bubble sort
algorithm.
(a.i) Describe the steps in the bubble sort algorithm that sorts the input data stored in the
SCORES and NAMES arrays in order of scores.
[5]
Markscheme
Award [5] max.
Award [1] for repeating the following steps until no swaps is required (the array is
sorted);
Award [1] for looping through the array SCORES;
Award [1] for comparing each pair of adjacent elements in the array SCORES;
Award [1] for swapping them if they are in the wrong order;
Award [1] for also swapping the corresponding elements in the array NAMES;
Examiners report
Generally, well answered, with many full or near full marks awarded. Candidates
were required to describe the main steps involved in the bubble sort algorithm.
Many candidates were well prepared, some candidates even wrote their answers
in pseudocode.
[1]
Markscheme
Award [1] max.
Selection sort;
Insertion sort:
Quick sort;
Merge sort;
Shell sort;
A decision has been made to create a new application. It will use a binary tree as an alternative
to the two arrays.
[3]
Markscheme
Award [3] max.
Components data / two data fields: name and score;
pointer to the left child;
pointer to the right child;
(c) The input data will be inserted into the binary tree so that an inorder traversal of the binary
tree would output all the students’ names and scores, sorted from the highest to the lowest
score.
[6]
Markscheme
Award [6] max.
Award [1] for a loop (to input all the data)
Award [1] for placing the inputted data into a newly created node
Award [1] for setting the root node to the new node (if the tree is empty/ no root
node)
Award [1] for start searching from the root node
Award [1] for searching for the empty location in the left subtree if the input score
is higher than the current value
Award [1] for inserting the new node in the left subtree when the proper location is
found
Award [1] for searching for the empty location in the right subtree if the input
score is lower than the current value
Award [1] for inserting the new node in the right subtree when the proper location
is found
Example 1:
Repeat the following steps (until all the names and scores are inputted);
input the values (name and score of one student), create a new node and
place the input values into the newly created node;
If the tree is empty, set the root to a new node;
Else (if the tree is not empty)
repeat the following until a leaf node is reached;
If a new node is smaller than or equal to the node (here it is a root
node)
move to its right child;
If a new node is larger than the node, move to its left child:
insert the new node (as a right or left child of the leaf node based on
node
is less or greater than the leaf node);
Example 2:
Repeat the following steps (until all the names and scores are inputted);
Create a new node (for example, named ITEM); input the values (name and score
of one student) and place them into the new node (ITEM) ( and set its left and
right to NULL);
If there isn't a root node, set the root node to ITEM;
If there is a root node, start searching from the root node (to find ITEM's proper
location),
if the score in ITEM is greater than the score in the root search for the
empty
location in the left subtree;
otherwise (if the score in ITEM is lesser than the score in the root), search for the
empty location in the right subtree;
insert ITEM into empty location;
Example 3:
While the end of the input list is not reached do the following;
input the values (name and score of one student), create a new node
and place the input values into the newly created node;
if there is no root node, set the root to the new node;
if there is a root node
start from the root node and if the score in the node to insert is less
than
the root, go to right child;
otherwise go to the left child of the root;
continue this process (Note: each node is a root for some subtree) until
a null pointer (or leaf node) is found ( where it is not possible to go any
further);
when the leaf node is found, insert the node as a right or left child of the leaf node
( based on node is less or greater than the leaf node);
Examiners report
The majority of students attempted it and many got it right.
9. 22N.1.HL.TZ0.14
An integer divisor of an integer, N(N>0), is an integer greater than zero that divides N without
leaving a remainder. The proper divisors of N are divisors of N other than N itself.
For example:
(a) Construct a logic expression that evaluates to True if X is a proper divisor of Y and to False
otherwise.
[2]
Markscheme
Award [2] max.
Award [1] for checking that the remainder in integer division is equal to zero
Award [1] for also checking that X is not equal to Y.
Example:
(Y mod X == 0) and (X != Y)
Note: Accept % instead of mod. Accept && instead of and.
Accept other correct expressions such as (X ≠ Y) and (trunc(Y/X)*X = Y).
Examiners report
Most of students constructed the logic expression and many got it right.
The subprogram sumPD(N) accepts an integer, N(N>1), and returns the sum of all proper
divisors of N. For example, sumPD(16) returns 15 (1 + 2 + 4 + 8 = 15).
[3]
Markscheme
Award [3] max.
sumPD(N)
SUM=0
loop I from 1 to N div 2
// Accept as upper boundary N//2 OR N−1
// OR a java expression:(int)Math.round(Math.sqrt(N))
if N mod I==0
then SUM=SUM+I
end if
end loop
return SUM
end sumPD
Note: the subprogram heading and the return statement may not appear in the
candidate's response.
Examiners report
(b) and Part (c), algorithms were required based on the question scenario.
Few candidates did not attempt these questions.
Some candidates earned full marks by demonstrating excellent programming
skills.
A large number of candidates scored several marks for the construction of a
partial solution or a solution that was partially correct.
(c) Every number can be classified as abundant, deficient, or perfect according to the following
definitions:
A number is an abundant number if it is less than the sum of its proper divisors. For example,
12 is an abundant number because 1 + 2 + 3 + 4 + 6 = 16, and 16 > 12.
A number is a deficient number if it is greater than the sum of its proper divisors. For example,
9 is a deficient number because 1 + 3 = 4, and 4 < 9.
A number is a perfect number if it is equal to the sum of its proper divisors. For example, 28 is
a perfect number because 1 + 2 + 4 + 7 + 14 = 28, and 28 = 28.
An algorithm should be written that creates three one-dimensional arrays, named ABUNDANT,
DEFICIENT and PERFECT, so that
• the array ABUNDANT holds all the abundant numbers of the two-dimensional array MAT
• the array DEFICIENT holds all the deficient numbers of the two-dimensional array MAT
• the array PERFECT holds all the perfect numbers of the two-dimensional array MAT.
For example, if the 4 × 6 two-dimensional array MAT holds 24 positive integers, as follows:
You may assume that the two-dimensional array MAT is inputted and three one‑dimensional
arrays of sufficient size are initialized.
[10]
Markscheme
Award [10] max.
Award [1] for initializing indexes in all three arrays
Award [1] for correct outer loop
Award [1] for correct inner loop
Award [1] for calling the subprogram correctly
Award [1] for correctly accessing element of MAT (correct row and column
indexes)
Award [1] for correct use of if statements
Award [1] for checking if MAT[R][C] is perfect and increasing the array PERFECT
index
Award [1] for placing MAT[R][C] at correct place in array PERFECT
Award [1] for checking if MAT[R][C] is abundant and increasing the array
ABUNDANT index
Award [1] for placing MAT[R][C] at correct place in the array ABUNDANT
Award [1] for checking if MAT[R][C] is deficient and increasing the array
DEFICIENT index
Award [1] for placing MAT[R][C] at correct position in array DEFICIENT
Example 1
IP=−1
ID=−1
IA=−1
loop R from 0 to 3 // Accept MAT.length() OR len(MAT) instead of 3
loop C from 0 to 5// Accept MAT[R].length() OR len(MAT[R])instead of 5
X = sumPD (MAT[R][C]) //calls the sumPD()subprogram
if X == MAT[R][C] //checking if perfect
then
IP=IP+1
PERFECT[IP]= MAT[R][C]
else if X > MAT[R][C] //checking if abundant
then
IA=IA+1
ABUNDANT[IA]= MAT[R][C]
else
ID=ID+1
DEFICIENT[ID]= MAT[R][C]
end if
end if
end loop
end loop
Example 2
IP=0
ID=0
IA=0
loop R from 0 to 3
loop C from 0 to 5
if sumPD(MAT[R][C])== MAT[R][C]
then
PERFECT[IP]= MAT[R][C]
IP=IP+1
end if
if sumPD( MAT[R][C])> MAT[R][C]
then
ABUNDANT[IA]= MAT[R][C]
IA=IA+1
end if
if sumPD( MAT[R][C])< MAT[R][C]
then
DEFICIENT[ID]= MAT[R][C]
ID=ID+1
end if
end loop
end loop
10. 22M.1.HL.TZ0.10
[2]
Markscheme
Award [2 max]
Child (is either null or) is a node that has up to two references /links to other
nodes;
and has (only) one predecessor (parent) node;
“Child” is every node in a binary tree which is descendant/ the node which has a
link from its predecessor (the node which is a predecessor of any node is called
as parent node);
The child node can have up to two descendants (child nodes);
(All the nodes except the node which is the origin of the binary tree data structure
(called root) are child nodes;)
Examiners report
This question generated responses that were a little vague.
11. 22M.1.HL.TZ0.9
[1]
Markscheme
Award [1 max]
A linear (abstract) data structure;
First in First out/FIFO;
Elements can only be added at one end(rear/tail) and removed from the other
(front/head);
Once a new element is inserted into the queue (enqueue), all the elements
inserted before the new element in the queue must be removed (dequeue), to
remove the new element;
Examiners report
Many candidates correctly answered this question.
[1]
Markscheme
Award [1 max]
Print queue;
CPU task scheduling;
Simulation of a real-life scenario (call centre, supermarket queue);
Playlist queue;
Interrupt queues;
Queues in routers and switches;
Mail queues;
Buffers in devices like keyboard;
Website traffic;
Note to examiners: Reward other reasonable responses.
Examiners report
Many candidates correctly answered this question.
12. 22M.1.HL.TZ0.15
Reverse Polish notation (RPN) is a method used to represent mathematical expressions so they
can be evaluated without the need for parentheses.
An expression written in this form is known as postfix notation, whereas an expression written
the traditional way is known as infix notation.
For example:
Infix notation: (8 − 5) * 7
Postfix notation: 8 5 − 7 *
Both the infix and postfix expressions have the same result: 21
– if it is a mathematical operator, the last two digits are popped from the stack and
evaluated as though the current operator was between them. The result of this operation
is then pushed back onto the stack.
• The process is repeated until all the characters in the RPN expression have been used.
A collection named RPN already stores an expression formatted in Reverse Polish notation.
The algorithm reads the values from the collection and, using a stack data structure, evaluates it.
RPN.resetNext()
loop while RPN.hasNext()
VALUE = RPN.getNext()
loop while not (VALUE = "+" or VALUE = "-" or VALUE = "*" or VALUE = "/")
stack.push(VALUE)
VALUE = RPN.getNext()
end loop
OPERAND2 = stack.pop()
OPERAND1 = stack.pop()
if VALUE = "+" then
NEW_VAL = OPERAND1 + OPERAND2
stack.push(NEW_VAL)
end if
if VALUE = "-" then
NEW_VAL = OPERAND1 - OPERAND2
stack.push(NEW_VAL)
end if
if VALUE = "*" then
NEW_VAL = OPERAND1 * OPERAND2
stack.push(NEW_VAL)
end if
if VALUE = "/" then
NEW_VAL = OPERAND1 / OPERAND2
stack.push(NEW_VAL)
end if
end loop
RESULT = stack.pop()
output "The result is: ", RESULT
(a) Copy and complete the trace table for the algorithm using the RPN collection data:
5 2 + 25 16 − * 3 /
[6]
Markscheme
Award [6 max]
Award [1] for correct values in VALUE column;
Award [1] for correct values of OPERAND2, OPERAND1 and NEW_VAL when
VALUE is ‘+’;
Award [1] for correct values of OPERAND2, OPERAND1 and NEW_VAL when
VALUE is ‘-’;
Award [1] for correct values of OPERAND2, OPERAND1 and NEW_VAL when
VALUE is ‘*’;
Award [1] for correct values of OPERAND2, OPERAND1 and NEW_VAL when
VALUE is ‘/’;
Award [1] correct output: ‘The result is: 21’;
Note: The trace table may be differently presented.
Note: Allow Follow Through.
Examiners report
Most candidates had difficulty tracing the algorithm in Part (a).
There were some candidates who did not attempt question 15.
(b) Explain why a stack is used in the process of evaluating the expression in the algorithm.
[3]
Markscheme
Award [3 max]
A stack is a last in first out (LIFO) / first in last out (FILO) data structure;
…which means data is popped off the stack in the reverse order to which it was
pushed;
In the expression, it is important to evaluate some of the values in a certain
order(to obtain the correct result);
For example, 25 − 16 would give the wrong value if it was evaluated as 16 − 25;
Pushing items onto a stack and then popping them off reverses the order;
To evaluate e.g. “10 2 /” we must treat it as “do the operation on the operands 10
and 2”/ i.e. we have to access the operator before we can apply it to the
operands;
A stack achieves the reversing of the order of the operators and their operands as
a group (but it also reverses the operands which must be fixed);
Examiners report
Part (b) was reasonably well answered with many gaining at least 1 or 2 of the
marking points.
An alternative data structure in which the expression used in part (a) may be stored is a binary
tree. If the tree is traversed using postorder tree traversal, the output is formatted in RPN.
(c) Outline the steps involved in traversing the given tree using postorder tree traversal.
[4]
Markscheme
Award [4 max]
Start from the root node;
If the root is null, return immediately;
Traverse left subtree;
Traverse right subtree;
Visit root;
start from the root node (for example traverse (root)) ;
terminate traversal (and backtrack) when/if root equals null;
(before visiting the root node) traverse (and visit/process/output) each node in the
left subtree (i.e., traverse(root.left));
(before visiting the root node) traverse (and visit/process/output) each node in the
right subtree (i.e., traverse(root.right));
visit/output/process root (for example, output(root));
Examiners report
Only a few candidates earned full marks in Part (c).
(d) State the output from the given tree using inorder tree traversal.
[2]
Markscheme
Award [2 max]
Award [1] if the answer contains no more than one error.
(5+2)*(25−16)/3
Note to examiners: Ignore the brackets – these represent the completely correct
mathematical expression, but they are not read from the tree. Some candidates
might include them because they realise that they may be needed so the
expression works correctly.
13. 21N.1.HL.TZ0.12
where head is an external pointer that points to the first node in the circular linked list.
Three operations are performed on this circular linked list in the following order:
[3]
Markscheme
Award [3 max].
Award [1] for the node containing number 20 is pointed to by the pointer 'head';
Award [1] for the diagram showing only two nodes and all the correct links;
Award [1] for the last node containing number 5;
Examiners report
Most candidates were able to sketch a diagram showing the resulting circular
linked list.
(b) Outline how the last node of the circular linked list is identified.
[2]
Markscheme
Award [2 max].
The last node is identified by its next/link pointer;
which contains the address of the node at the beginning of the list / is equal to the
pointer “head “;
Examiners report
A mixed set of responses was seen for this question. Most candidates knew that
the last node in a circular linked list contains a pointer to the first node of the list.
A few candidates incorrectly wrote that the next of the last node point to the null.
(c) Describe the steps required to calculate the sum of all numbers held in this circular linked list.
[4]
Markscheme
Award [4 max].
Initialize (a temporary pointer with the head and) a variable sum with 0 (zero);
Loop from the beginning to the end of the circular linked list / until all the nodes
get traversed);
Add the value (of the data field) (of the current node) to the sum;
Change the temporary pointer so it points the next node of circular linked list;
Note: Answers written in pseudocode are acceptable.
For example,
sum = 0
curr = head
loop
sum = sum + curr.data
curr = curr.next
until curr == head
Examiners report
Candidates were required to write the main steps involved in an algorithm to
calculate the sum of all numbers held in the circular linked list. Many candidates
were well prepared, some candidates even wrote their answers in algorithmic
form and they generally achieved better results than those who simply described
the steps. The full range of marks, from zero to four were achieved for this
question.
Arrays and linked lists are used to store linear data.
[4]
Markscheme
Award [4 max].
In an array, memory is assigned during compile time(predetermined) whilst in a
linked list it is allocated during execution/runtime;
Arrays are of fixed size whilst linked lists are flexible and can expand and contract
its size;
Array requires less memory (due to actual data being stored within the index in
the array) whilst there is a need for more memory in linked list (due to storage of
additional next and previous pointers/references);
Elements are stored consecutively in array whereas elements are stored
randomly in linked lists;
Memory utilization is inefficient in the array whilst memory utilization is efficient in
the linked list;
Accessing an element in an array is direct (fast) while accessing an element in
linked list is sequential/linear (slower) /to get into the nth element only the array
name with index within the square bracket should be written whilst a linked list (to
get the nth element) should be traversed starting from the beginning of the list,
and traversing through the list until found/ ;
Operations like insertion and deletion in arrays consume a lot of time whilst the
performance of these operations in linked lists is fast;
Examiners report
Was reasonably well answered with many gaining at least two of the marking
points. Some candidates described two data structures individually without
performing any comparison and thus losing marks.
[2]
Markscheme
Award [2 max].
Print queues (a number of print jobs on a queue instead of waiting for each one to
finish before specifying the next one);
Queue is used for synchronization when data is transferred asynchronously
between two processes (for example IO Buffers, file IO);
Queues are used in CPU scheduling algorithms;
Handling of interrupts in real-time systems (the interrupts are handled in the same
order as they arrive, first come first served);
Computer modelling of physical queues (supermarket checkouts) (call centre
phone systems use queues to hold people calling them in an order, until a service
representative is free);
Examiners report
Was well answered.
14. 21N.1.HL.TZ0.5
(a) Identify one difference between a binary tree and a non-binary tree.
[1]
Markscheme
Award [1 max]
Binary tree (is a tree) in which every node has (no, one or) at most two children
whilst
a non binary tree can have nodes with more than 2 children (non binary trees do
not have an upper limit on number of children nodes);
Each node in a binary tree can have at most two subtrees (left and right subtree),
a node in a non binary tree can have any number of subtrees;
Examiners report
In this question both parts, (a) and (b) were well answered by the majority of
candidates.
(b) Given the following binary search tree (BST), draw the resulting BST after the deletion of the
root node.
[2]
Markscheme
Award [2 max]
Award [1] for the root (1)
Award [1] for the correct right subtree
Alternative answer
Examiners report
In this question both parts, (a) and (b) were well answered by the majority of
candidates. Part(b) Only a few candidates did not draw the resulting binary tree
after deleting the root node.
15. 21N.1.HL.TZ0.13
A bus company provides services within a city. Passengers can look up the distance between
any two bus stations on any of its routes.
For each route, a one-dimensional string array is used to store the names of all bus stations on
the route and a two-dimensional array is used to store the distances between the bus stations (in
kilometres). Only the lower triangle of the two-dimensional array is used to store the distances.
Figure 1 shows data about Route X, a bus route between Oppox and Dovely.
Figure 1: One-dimensional string array, ROUTE_X_NAMES, and
two-dimensional array, ROUTE_X_DISTANCES, for Route X
For example, the distance between Kingsley and Kronos (2.0 kilometres) can be found in
ROUTE_X_DISTANCES [7][5].
[1]
Markscheme
Award [1 max].
5.9;
Examiners report
The majority of students attempted it, and many got it right.
The two-dimensional array ROUTE_X_DISTANCES is valid if all the entries on and above the
main diagonal are zero and all the entries below the main diagonal are greater than zero.
[5]
Markscheme
Award [5 max].
Award [1] for correct outer/row loop
Award [1] for correct inner/column loop
Award [1] for use of a flag
Award [1] for checking whether all elements on and above the main diagonal are
zero
Award [1] for checking all elements below the main diagonal (they all should be
positive numbers)
Award [1] for outputting the appropriate message
Example 1:
VALID=True
loop R from 0 to 9
loop C from 0 to 9
if R>C and ROUTE_X_DISTANCES[R][C]<=0
then VALID=False
end if
if R<=C and ROUTE_X_DISTANCES[R][C]!=0
then VALID=False
end if
end loop
end loop
if VALID
then output('VALID')
else output('INVALID')
end if
Example 2:
FLAG=1
loop R from 1 to 9
loop C from 0 to R-1
if ROUTE_X_DISTANCES[R][C]<=0
then FLAG=0
end if
end loop
end loop
loop R from 0 to 9
loop C= from R to 9
if ROUTE_X_DISTANCES[R][C]!=0
then FLAG=0
end if
end loop
end loop
if FLAG ==1
then output('IT IS VALID')
else output('IT IS NOT VALID')
end if
Example 3:
Note: Marks should also be awarded if a candidate wrote the algorithm in
Java/Python/Javascript.
Award [1] for correct outer/row loop
Award [1] for correct inner/column loop
Award [1] for stopping as soon as an incorrect value is found
Award [1] for checking whether elements on and above the main diagonal are
zero
Award [1] for checking elements below the main diagonal (they all should be
positive numbers)
Award [1] for outputting the appropriate message
function check()
output("ROUTE_X_DISTANCES is "+check());
Examiners report
Algorithms were required based on the question scenario. Some candidates did
not attempt these questions. Some candidates achieved high marks by
demonstrating good programming skills. Many candidates scored several marks
for the construction of a partial solution or a solution that was partially correct.
(c) Construct an algorithm in pseudocode that inputs the names of two bus stations and outputs
the distance between them. If any of the inputted names are not found, the method should
output an appropriate message.
[6]
Markscheme
Award [6 max].
Award [1] for all variables correctly declared and initialized;
Award [1] for looping through the array ROUTE_X_NAMES;
Award [1] for determining positions of the first name in the array;
Award [1] for determining positions of the second name in the array;
Award [1] for outputting a message if one or other not present;
Award [1] for a comparison of positions to find largest;
Award [1] for the correct output of distance from ROUTE_X_DISTANCES;
Example 1:
NAME1=input()
NAME2=input()
POS1=-1
POS2=-1
K=0
loop while K<=9 and (POS1==-1 or POS2==-1)
if ROUTE_X_NAMES [K].equals(NAME1) //accept '==' instead of equals()
then POS1=K
end if
if ROUTE_X_NAMES [K].equals(NAME2)
then POS2=K
end if
K=K+1
end while
if POS1==-1 OR POS2==-1
then output('stations are not found')
else
if POS1 > POS2
then output(ROUTE_X_DISTANCES [POS1][POS2])
else output(ROUTE_X_DISTANCES [POS2][POS1])
end if
end if
Example 2:
ST1=input()
ST2=input()
PS1=-1
PS2=-1
loop K from 0 to 9
if ROUTE_X_NAMES [K]==ST1
then PS1=K
end if
if ROUTE_X_NAMES [K]==ST2
then PS2=K
end if
end loop
if PS1!=-1 AND PS2!=-1
then if PS1 < PS2
then T=PS1
PS1=PS2
PS2=T
end if
output(ROUTE_X_DISTANCES [PS1][PS2])
else
output('stations not found')
end if
Example 3:
Note: Award marks if algorithm is presented in a Java/Python/Javascript/any
other program rather than IB pseudocode.
For example, please see the following Javascript program
function findStation(station)
{ var found = false;
var i = 0;
do
{ found = (ROUTE_X_NAMES[i] == station);
if (!found) i = i + 1;
} while (!found && i < 10);
if (found) return i;
else
{ output("No such bus station as "+station);
return -1;
}
}
Examiners report
Algorithms were required based on the question scenario. Some candidates did
not attempt these questions. Some candidates achieved high marks by
demonstrating good programming skills Many candidates scored several marks
for the construction of a partial solution or a solution that was partially correct.
(d) The array ROUTE_X_TIMES (Figure 3) stores the approximate number of minutes it takes
for a bus to travel to a bus station from the previous one. For example, ROUTE_X_TIMES
[6] stores the number of minutes it takes for a bus to travel from Kingsley to Allapay: 7
minutes.
Explain how this data could be used to determine the number of minutes it takes for a bus to
travel between any two bus stations.
[3]
Markscheme
Award [3 max].
Determine positions/indexes/subscripts of both bus stations in array
ROUTE_X_NAMES;
Calculate the sum of the elements of array ROUTE_X_TIMES (calculate the
number of minutes as the sum of the array elements);
Between (lower +1) index and higher index;
Examiners report
Varied from poor to excellent.
16. 21M.1.HL.TZ0.10
[2]
Markscheme
Award [2 max]
Dynamic data structure does not have predetermined size/ allows memory use to
change as needed (no fixed size) / if more space is required to store more data, it
can therefore increase;
Can be expanded until all the available RAM is used;
There is no unused/wasted memory;
Memory is allocated to the data structure as the program executes (run-time);
Elements of a dynamic data structure are stored in memory locations that are
chained together but not necessarily physically contiguous;
Elements of a dynamic data structure are sequentially accessed;
Examiners report
Most candidates were able to identify two characteristics of a dynamic data
structure.
Most candidates were able to identify two characteristics of a dynamic data
structure.
17. 21M.1.HL.TZ0.11
Sketch a balanced binary tree that would allow the following output when traversed using in
order traversal:
[3]
Markscheme
Award [3 max]
Correct root;
Correct left sub-tree;
Correct right sub-tree;
Note: Award 1 mark for any binary tree with the same number of nodes in the left
and right subtree;
Examiners report
A balanced binary tree was not always familiar to candidates.
18. 20N.1.HL.TZ0.13
Each element of MAT holds a number for a colour; 1 represents the colour black and 0
represents the colour white.
In an application, the black-and-white image can be inverted (all white pixels are changed to
black, and all black pixels are changed to white).
Method invert(N,A) accepts a positive integer N and an N × N two-dimensional array A that holds
the data for a simple black-and-white image; it returns the inverted N × N two-dimensional array
A.
[3]
Markscheme
Award [3 max]
Award [1] for nested loops/loop through all array elements;
Award [1] for checking the array element for the number of colour;
Award [1] for updating correctly each of the array elements;
Example 1:
loop for I=0 to N-1
loop for J=0 to N-1
if A[I][J]==1
then A[I][J]=0
else A[I][J]=1
end if
end loop
end loop
Example 2:
R=0
C=0
I=0
loop while I< N*N
if A[R][C]==0
then A[R][C]=1
else A[R][C]=0
end if
C=C+1
if C>9 then
C=0
R=R+1
end if
I=I+1
end loop
Examiners report
This was answered well.
This would mean the first row of the original MAT is the last column in the rotated MAT, the
second row is the second-to-last last column, … and the last row is the first column.
where:
• N is an integer and A is the N × N two-dimensional array that holds data about an image
• K(K>=0) is an integer showing how many times the image should be rotated
(b.i) State the number of degrees by which the image will be rotated if the input value of K is 3.
[1]
Markscheme
Award [1 max]
270 (degrees);
Examiners report
The question was well answered with many gaining full marks.
(b.ii) Outline why it is more efficient that the loop in the given algorithm fragment executes (K
mod 4) times instead of K times. You may give an appropriate example in your answer.
[2]
Markscheme
Award [2 max]
A rotation by 360 degrees returns the image/matrix to its original value, so no
action need be taken. A rotation by 360+N degrees is equivalent to a rotation by
N degrees(this logic repeats, so for 90 degree rotations, there are only 3
transformations needed: by 90, by 2*90 and by 3*90);
making more is unnecessary/inefficient;
Unnecessary calls to the method rotate() which would make the algorithm less
efficient are avoided;
for example, repeating 10 times and repeating 2 (=10 mod 4) times, both return
the array holding the image rotated by 180 degrees;
NOTE: Accept any appropriate example, with any value of K which is greater than
or equal to 4;
Examiners report
The question was well answered with many gaining full marks.
The algorithm for method rotate(N,A) uses an additional N × N two-dimensional array, named
The N × N dimensional array B is initialized and updated using the values from A to
represent the image rotated clockwise by 90°.
(c) Construct the algorithm in pseudocode for the method rotate(N,A) described above.
[3]
Markscheme
Award [3 max]
Award [1] for completely correct nested loops;
Award [1] for correctly determining row indexes (in both matrixes, A and B);
Award [1] for correctly determining column indexes (in both matrixes, A and B);
NOTE: The method heading and return statement may not appear in the answers.
Only an algorithm for the method rotate() is requested.
Example:
rotate(N,A)
// initialize two dimensional array B
// for example, int[][] B = new int[N][N];
return B
end rotate
Examiners report
Answers to this question vary from poor to excellent. Some candidates
constructed excellent algorithms and they gained full marks on this question.
(d) To avoid inefficient use of memory, a new algorithm for the method rotate(N,A) is constructed.
The N × N two-dimensional array A should be rotated clockwise by 90°, without the use of any
additional arrays.
One way of rotating the two-dimensional array A clockwise by 90° is to transpose A, and then
reverse each row of A.
The transpose of A is formed by turning all the rows of A into columns. For example, the value in
the first row and third column (A[1][3]) is swapped with the value in the third row and first
column (A[3][1]).
Construct the new algorithm in pseudocode for the method rotate(N,A) described above.
[6]
Markscheme
Award [6 max]
Example:
(Transposes the two-dimensional array and then reverses each row.)
Award [3] for transposing.
Award [1] for the correct outer loop;
Award [1] for the correct inner loop;
Award [1] for the correct swap;
Award [3] for reversing each row of the transposed matrix.
Award [1] for the correct outer loop;
Award [1] for the correct inner loop;
Award [1] for the correct swap;
Award [1] for using nothing but a temporary variable to achieve this / no additional
/ extra space used except one temporary variable;
NOTE: The method heading and return statement may not appear. Only the
algorithm for the method rotate() is requested.
rotate (N,A)
//transposes A
loop for I=0 to N-1
loop for J=0 to I-1
TEMP = A[I][J]
A[I][J] = A[J][I]
A[J][I] = TEMP
end loop
end loop
// reverses each row of transposed matrix A
loop for I=0 to N-1
loop for J=0 to N div 2-1
TEMP = A[I][J]
A[I][J] = A[J][I]
A[J][I] = TEMP
end loop
end loop
return A
end rotate
Examiners report
Answers to this question vary from poor to excellent. Some candidates
constructed excellent algorithms and they gained full marks on this question.
19. 20N.1.HL.TZ0.12
(a) Describe one difference between stack and queue data structures.
[2]
Markscheme
Award [2 max]
In a stack, the same end is used to insert and delete the elements;
whilst two different ends are used in the queue to insert and delete the elements;
Stack has only one open end so only one pointer is used to refer to the top of the
stack;
but queue has two open ends and two pointers should be used (to refer front and
the rear end of the queue);
Queue is a first-in-first-out (FIFO) data structure;
and stack is last-in-first-out (LIFO) data structure;
Examiners report
Well answered question.
enqueue()
[1]
Markscheme
Award [1 max]
(enqueue) adds an item to rear/tail of the queue;
Examiners report
Candidates mostly gave good responses for this question.
dequeue()
[1]
Markscheme
Award [1 max]
(dequeue) removes an item from front/head of the queue;
Examiners report
Candidates mostly gave good responses for this question.
isEmpty()
[1]
Markscheme
Award [1 max]
(isEmpty)
checks if the queue is empty or not;
returns TRUE if the queue is empty, FALSE otherwise;
Examiners report
Candidates mostly gave good responses for this question.
Construct an algorithm in pseudocode for reversing the queue using a stack data structure.
You may assume that the data in the queue is input and a new empty stack is created.
Only the standard queue and stack operations are allowed.
[5]
Markscheme
Award [5 max]
Award [1] for a while loop (through queue);
Award [1] for placing each item removed from the beginning of the queue to the
top of the stack;
Award [1] for a while loop (through stack);
Award [1] for adding each element popped from the stack to the end of the
queue;
Award [1] for the correct use of stack and queue methods;
Example:
//S is a new/created empty stack
// push all of the elements of Q to stack
while not Q.isEmpty()
X=Q.dequeue()
S.push(X) // OR S.push(Q.dequeue())
end while
Examiners report
A few candidates did not attempt this question. However, those who did generally
answered well. A few candidates incorrectly used 'enqueue' operations also for
the stack.
mystery(N)
if N>0 then
return 3 + mystery(N-3)
else
return 3
end if
end mystery
where N is an integer.
[3]
Markscheme
Award [3 max]
mystery(7)= 3 + mystery(4);
= 3 +3 + mystery(1) ;
= 3 +3 + 3 +mystery(-2)=3+3+3+3=12 ;
NOTE: Award only [1] if the working is not shown and only the final result is given.
Examiners report
A simple enough recursive algorithm, leading to a high number of correct
answers.
Markscheme
Award [2 max]
More difficult/complicated to code;
if the data structure being processed is not recursive;
It is difficult to find bugs;
particularly while using global variables;
Can use more memory (than iterative solution) when executed;
because every recursive call increases the call stack;
Recursion to a deeper level will be difficult/impossible to implement;
if the call stack space on the system is limited;
Slower execution / using a recursive function takes more time to execute;
as compared to its non- recursive/ iterative counterpart;
20. 20N.1.HL.TZ0.2
[1]
Markscheme
Award [1 max]
B, A, D, C;
Examiners report
Straightforward question which caused few problems. Some candidates confused
in-order with pre-order traversal.
(b) State the result of preorder traversal of this binary tree.
[1]
Markscheme
Award [1 max]
A, B, C, D;
Examiners report
Straightforward question which caused few problems. Some candidates confused
in-order with pre-order traversal.
21. 20N.1.HL.TZ0.12
(a) Describe one difference between stack and queue data structures.
[2]
Markscheme
Award [2 max]
In a stack, the same end is used to insert and delete the elements;
whilst two different ends are used in the queue to insert and delete the elements;
Stack has only one open end so only one pointer is used to refer to the top of the
stack;
but queue has two open ends and two pointers should be used (to refer front and
the rear end of the queue);
Queue is a first-in-first-out (FIFO) data structure;
and stack is last-in-first-out (LIFO) data structure;
Examiners report
Well answered question.
enqueue()
[1]
Markscheme
Award [1 max]
(enqueue) adds an item to rear/tail of the queue;
Examiners report
Candidates mostly gave good responses for this question.
(b.ii) State the purpose of the following queue method:
dequeue()
[1]
Markscheme
Award [1 max]
(dequeue) removes an item from front/head of the queue;
Examiners report
Candidates mostly gave good responses for this question.
isEmpty()
[1]
Markscheme
Award [1 max]
(isEmpty)
checks if the queue is empty or not;
returns TRUE if the queue is empty, FALSE otherwise;
Examiners report
Candidates mostly gave good responses for this question.
You may assume that the data in the queue is input and a new empty stack is created.
Only the standard queue and stack operations are allowed.
[5]
Markscheme
Award [5 max]
Award [1] for a while loop (through queue);
Award [1] for placing each item removed from the beginning of the queue to the
top of the stack;
Award [1] for a while loop (through stack);
Award [1] for adding each element popped from the stack to the end of the
queue;
Award [1] for the correct use of stack and queue methods;
Example:
//S is a new/created empty stack
// push all of the elements of Q to stack
while not Q.isEmpty()
X=Q.dequeue()
S.push(X) // OR S.push(Q.dequeue())
end while
Examiners report
A few candidates did not attempt this question. However, those who did generally
answered well. A few candidates incorrectly used 'enqueue' operations also for
the stack.
mystery(N)
if N>0 then
return 3 + mystery(N-3)
else
return 3
end if
end mystery
where N is an integer.
[3]
Markscheme
Award [3 max]
mystery(7)= 3 + mystery(4);
= 3 +3 + mystery(1) ;
= 3 +3 + 3 +mystery(-2)=3+3+3+3=12 ;
NOTE: Award only [1] if the working is not shown and only the final result is given.
Examiners report
A simple enough recursive algorithm, leading to a high number of correct
answers.
[2]
Markscheme
Award [2 max]
More difficult/complicated to code;
if the data structure being processed is not recursive;
It is difficult to find bugs;
particularly while using global variables;
Can use more memory (than iterative solution) when executed;
because every recursive call increases the call stack;
Recursion to a deeper level will be difficult/impossible to implement;
if the call stack space on the system is limited;
Slower execution / using a recursive function takes more time to execute;
as compared to its non- recursive/ iterative counterpart;
22. 20N.1.HL.TZ0.13
Each element of MAT holds a number for a colour; 1 represents the colour black and 0
represents the colour white.
In an application, the black-and-white image can be inverted (all white pixels are changed to
black, and all black pixels are changed to white).
Method invert(N,A) accepts a positive integer N and an N × N two-dimensional array A that holds
the data for a simple black-and-white image; it returns the inverted N × N two-dimensional array
A.
[3]
Markscheme
Award [3 max]
Award [1] for nested loops/loop through all array elements;
Award [1] for checking the array element for the number of colour;
Award [1] for updating correctly each of the array elements;
Example 1:
loop for I=0 to N-1
loop for J=0 to N-1
if A[I][J]==1
then A[I][J]=0
else A[I][J]=1
end if
end loop
end loop
Example 2:
R=0
C=0
I=0
loop while I< N*N
if A[R][C]==0
then A[R][C]=1
else A[R][C]=0
end if
C=C+1
if C>9 then
C=0
R=R+1
end if
I=I+1
end loop
Examiners report
This was answered well.
This would mean the first row of the original MAT is the last column in the rotated MAT, the
second row is the second-to-last last column, … and the last row is the first column.
K=input()
loop for M=0 to K mod 4 - 1
A=rotate(N,A)
end loop
where:
• N is an integer and A is the N × N two-dimensional array that holds data about an image
• K(K>=0) is an integer showing how many times the image should be rotated
(b.i) State the number of degrees by which the image will be rotated if the input value of K is 3.
[1]
Markscheme
Award [1 max]
270 (degrees);
Examiners report
The question was well answered with many gaining full marks.
(b.ii) Outline why it is more efficient that the loop in the given algorithm fragment executes (K
mod 4) times instead of K times. You may give an appropriate example in your answer.
[2]
Markscheme
Award [2 max]
A rotation by 360 degrees returns the image/matrix to its original value, so no
action need be taken. A rotation by 360+N degrees is equivalent to a rotation by
N degrees(this logic repeats, so for 90 degree rotations, there are only 3
transformations needed: by 90, by 2*90 and by 3*90);
making more is unnecessary/inefficient;
Unnecessary calls to the method rotate() which would make the algorithm less
efficient are avoided;
for example, repeating 10 times and repeating 2 (=10 mod 4) times, both return
the array holding the image rotated by 180 degrees;
NOTE: Accept any appropriate example, with any value of K which is greater than
or equal to 4;
Examiners report
The question was well answered with many gaining full marks.
The algorithm for method rotate(N,A) uses an additional N × N two-dimensional array, named
The N × N dimensional array B is initialized and updated using the values from A to
represent the image rotated clockwise by 90°.
(c) Construct the algorithm in pseudocode for the method rotate(N,A) described above.
[3]
Markscheme
Award [3 max]
Award [1] for completely correct nested loops;
Award [1] for correctly determining row indexes (in both matrixes, A and B);
Award [1] for correctly determining column indexes (in both matrixes, A and B);
NOTE: The method heading and return statement may not appear in the answers.
Only an algorithm for the method rotate() is requested.
Example:
rotate(N,A)
// initialize two dimensional array B
// for example, int[][] B = new int[N][N];
return B
end rotate
Examiners report
Answers to this question vary from poor to excellent. Some candidates
constructed excellent algorithms and they gained full marks on this question.
(d) To avoid inefficient use of memory, a new algorithm for the method rotate(N,A) is constructed.
The N × N two-dimensional array A should be rotated clockwise by 90°, without the use of any
additional arrays.
One way of rotating the two-dimensional array A clockwise by 90° is to transpose A, and then
reverse each row of A.
The transpose of A is formed by turning all the rows of A into columns. For example, the value in
the first row and third column (A[1][3]) is swapped with the value in the third row and first
column (A[3][1]).
Construct the new algorithm in pseudocode for the method rotate(N,A) described above.
[6]
Markscheme
Award [6 max]
Example:
(Transposes the two-dimensional array and then reverses each row.)
Award [3] for transposing.
Award [1] for the correct outer loop;
Award [1] for the correct inner loop;
Award [1] for the correct swap;
Award [3] for reversing each row of the transposed matrix.
Award [1] for the correct outer loop;
Award [1] for the correct inner loop;
Award [1] for the correct swap;
Award [1] for using nothing but a temporary variable to achieve this / no additional
/ extra space used except one temporary variable;
NOTE: The method heading and return statement may not appear. Only the
algorithm for the method rotate() is requested.
rotate (N,A)
//transposes A
loop for I=0 to N-1
loop for J=0 to I-1
TEMP = A[I][J]
A[I][J] = A[J][I]
A[J][I] = TEMP
end loop
end loop
// reverses each row of transposed matrix A
loop for I=0 to N-1
loop for J=0 to N div 2-1
TEMP = A[I][J]
A[I][J] = A[J][I]
A[J][I] = TEMP
end loop
end loop
return A
end rotate
Examiners report
Answers to this question vary from poor to excellent. Some candidates
constructed excellent algorithms and they gained full marks on this question.
23. 20N.2.HL.TZ0.16
A single parking space that holds one car can be used to hold two motorbikes. The programmer
has decided to use a two-dimensional array to create a map of the parking area.
(a.i) Identify one advantage of using a two-dimensional array for this purpose.
[1]
Markscheme
Award [1 max].
Faster to access (i.e. O1 instead of On);
Arrays take less memory than lists (as they do not store pointers);
Mirrors real life situation;
Examiners report
Both parts were well-answered.
(a.ii) Identify one disadvantage of using a two-dimensional array for this purpose.
[1]
Markscheme
Award [1 max].
Static, therefore memory wasted when not being fully utilised;
Inability to grow, should further spaces be added, i.e. If Parking area grows;
Examiners report
Both parts were well-answered.
Police have requested a way of searching the parking area for vehicles with a specified
registration plate, and a binary tree has been suggested.
(b) Outline why searching for the registration plate in a binary tree would be faster than looking
for it in the two-dimensional array.
[3]
Markscheme
Award [3 max].
The array would need to be searched using a linear search which is inefficient
O(n) whereas a binary search is much more efficient O(log n);
A linear search for a car in this parking area could require a maximum of 200
comparisons (i.e. it would look at the first row of every column) whereas a binary
search would only require 8 (i.e. log 200 base 2);
A linear search for a motorbike in this parking area would require a maximum of
400 comparisons (i.e. it would need to look at both rows of every column)
whereas a binary search would only require 7 (log 100 base 2);
In a binary search, each comparison would eliminate half of the remaining
possible matches, whereas in a linear search it only eliminates 1;
A binary search has the registration plate as its key and therefore it doesn’t
require accessing the field of the vehicle object for each comparison, whereas in
a linear search, each comparison would be slower because it would require
getting the vehicle object’s registration field using an accessor method;
A binary search is always faster than a linear search on a large data set. As the
police may be searching for many cars and in many parking areas, their searches
will be on large set of data;
Examiners report
Most students identified the tree property that effectively eliminates half of the tree
when searching but answers were not always detailed enough to gain full marks.
(c) Identify the steps that would be involved in taking the data from this two-dimensional array
and creating a binary search tree.
[5]
Markscheme
Award [5 max].
Create a binary tree to store vehicle objects;
Loop around all of the elements in the 2 dimensional array (e.g. using inner and
outer loop);
Skip empty locations;
Take the first vehicle found and add as the head of the binary tree;
Take all subsequent vehicles found and do the following;
Get the node’s vehicle registration;
Find the appropriate insertion point in the binary tree by navigating from the root
and comparing the registration to the key of the current node;
When a leaf node is reached compare the registration with the vehicle to be
inserted and insert it as the left or right child node, using its registration as the
key;
Continue until the end of the vehicle array has been reached;
Examiners report
A large number of students were unclear as to how a binary search tree is
created. Full marks were only reached by those students who clearly identified
the different stages of the process.
24. 19N.1.HL.TZ0.5
Sketch a double linked list that holds the following sequence of names: Anne, Lana, Mary.
[3]
Markscheme
Award [3 max]
Award [1] for showing that every node in a double linked list contains three fields
(data and 2 pointers);
Award [1] for showing every node has link to its previous node and next node/can
be traversed forward by using next field and can be traversed backward by using
previous field;
Award [1] for showing that the first node must be always pointed by an external
pointer (for example head) (and the last node could be pointed to by an external
pointer (for example rear));
Award [1] for showing that the previous field of the first node must be NULL and
the next field of the last node must be NULL.
Examiners report
Most candidates sketched a doubly linked list and answered this question
reasonably well.
Only a few candidates did not attempt this question.
25. 19N.1.HL.TZ0.12
[2]
Markscheme
Award [2 max]
Holding all data of a function/method call; simulation of recursion;
Conversion of expressions (infix to postfix, infix to prefix, etc.)
Evaluating expression;
Parsing;
Examiners report
Mostly well answered questions.
(b) Explain the use of a one-dimensional array as a static stack. Your answer should include
brief outlines of the push and pop operations and the tests for empty and full stacks.
[6]
Markscheme
Award [6 max]
Award [3 max] for the following:
An array A of N elements should be initialized (fixed, predetermined size);
keep track of the top of the stack since not all of the array holds stack elements
(in an integer variable, for example, named TOP);
the main property of a stack is that stack values/objects go on and come off of the
one end of the stack (LIFO data structure);
Award [1] for each stack method outlined.
Push
Places a value (object) on the top of the stack;
Increase TOP by one and set A[TOP]= value;
Pop
Returns a value from the top of the stack and removes that value from the top of
the stack;
Returns A[TOP] and decreases TOP by 1;
IsEmpty
Reports whether the stack is empty or not / returns True if the stack is empty,
False otherwise;
Returns True if TOP is less than 0, False otherwise;
IsFull
Reports whether the stack is full or not/ returns True is stack is full, False
otherwise;
Returns True if TOP is greater than N-1 (where N is size of the array), False
otherwise;
Examiners report
Not all candidates answered this question, but most of those who did outlined the
push and pop operations and the tests for empty and full stacks. The use of a
one-dimensional array as a static stack was weakly explained.
An inorder traversal of this binary tree will produce a list of names sorted in ascending order.
[1]
Markscheme
Award [1 max]
The names must be in the following order:
Elm, Elder, Holly, Rowan, Larch, Hazel;
Examiners report
Mostly well answered.
(c.ii) Draw the binary tree after deleting the root node.
[3]
Markscheme
Award [3 max]
Award [1] for the correct root.
Award [1] for the correct left subtree.
Award [1] for the correct right subtree.
Examiners report
Mostly well answered.
[3]
Markscheme
Award [3 max]
Static data structures are fixed sized (for example, arrays) whilst dynamic data
structure (for example, trees, linked lists) have flexible size;
The size of static data structures is predetermined; the amount of memory once
allocated to them at compile time cannot change on run time whereas dynamic
data structures they can grow or shrink as needed to contain the data to be
stored;
Slower access to elements of dynamic data structure (sequential access) when
compared with (direct) access to elements of static data structures;
Examiners report
Mostly well answered.
26. 19N.1.HL.TZ0.13
The following matrix has non-zero elements on the diagonal, on the super-diagonal (the first
diagonal above the main diagonal) and on the sub-diagonal (the first diagonal below the main
diagonal). All the rest of the elements are zeros.
𝑀𝐴𝑇
(a) State the value of MAT[3][4].
[1]
Markscheme
Award [1 max]
4;
Examiners report
Parts (a) and (b) have been attempted with some repetition. The reasonable
general knowledge of when and how data can be lost and backup strategies.
However, many responses were vague enough not to describe the situation with
reference to the basic technical terminology of the devices/systems.
For example, isValidMatrix(6,MAT) returns True for the matrix MAT given above.
[8]
Markscheme
Award [8 max]
Award [1] for initialization, correct changing and returning of a flag.
Award [1] for the nested loops.
Award [1] for correct initial and for correct terminal value and changing the value
of the control variable in outer loop.
Award [1] for correct initial and for correct terminal value and changing the value
of the control variable in inner loop.
Award [1] for efficiency (terminating execution when a zero or non-zero element
is not at the correct position).
Award [1] for correct condition in if statement.
Award [1] for checking elements in the lower/upper triangle.
Award [1] for checking elements on the three diagonals.
Award [1] for the correct logical expression.
Example 1:
INVALID=False
R=0
loop while R<N and not INVALID
C=0
loop while C<N and not INVALID
if abs(R-C)>=2 and A[R][C]!=0 or abs(R-C)<2 and
A[R][C]==0 then
INVALID=True
endif
C=C+1
endwhile
R=R+1
endwhile
return not INVALID
Please note that instead the logical expression given in the Example answer 1
several if statements could be used and award 1 mark for each correct if
statement (1 mark for checking elements in the lower triangle, 1 mark for
checking upper triangle, 1 mark for checking three diagonals).
if R>C and R-C>1 then //lower triangle
if A[R][C]!=0 then
INVALID=True
endif
endif
if R<C and C-R>1 then //upper triangle
if A[R][C]!=0 then
INVALID=True
endif
endif
if R<C and C-R=1 or R>C and R-C==1 or R==C then //three
diagonals
if A[R][C]==0 then
INVALID=True
endif
endif
Example 2:
Award [7 max] (no ‘efficiency’ mark).
Award [1] for initialization, correct changing and returning of a flag
Award [1] for the nested loops.
Award [1] for correct initial and for correct terminal value of the control variable in
outer loop.
Award [1] for correct initial and for correct terminal value of the control variable in
inner loop.
Award [1] for correct condition in if statement.
Award [1] for checking elements in lower/upper triangle.
Award [1] for checking elements on the three diagonals.
Award [1] for the use of correct logical expressions.
INVALID=False
loop R=0 to N-1 do
loop C=0 to N-1 do
if abs(R-C)>=2 and A[R][C]!=0 or abs(R-C)<2 and
A[R][C]==0 then
INVALID=True
endif
endloop
endloop
return not INVALID
Examiners report
The question was reasonably well answered with many gaining at least 2 or 3 of
the marking points.
Given the following recursive method mystery() with two formal parameters:
A (a two-dimensional array) and R (an integer).
mystery(A,R)
if R > 0 then
return A[R][R-1] + mystery(A,R-1)
else
return 0
end if
end mystery
(c) Determine the value of variable X after execution of the following method call:
X = mystery(MAT,5)
where MAT is the two-dimensional array given. You must show your working.
[4]
Markscheme
Award [4 max]
X = mystery( MAT, 5)= 5+ mystery( MAT, 4);
5 + 7 + mystery( MAT, 3);
5 + 7 −5 + mystery( MAT, 2);
5 + 7 −5 + 9 + mystery( MAT, 1);
5+7-5+9+1+mystery(MAT, 0)= 5+7-5+9+1+0 = 17;
Examiners report
Quite a few candidates did not attempt the recursion question. However, those
who did generally answered well.
[2]
Markscheme
Award [2 max]
Calculates the sum of R elements;
Starting from A[R][R-1] to A[1][0];
on the sub-diagonal (of the two-dimensional array A);
Examiners report
Quite a few candidates did not attempt the recursion question. However, those
who did generally answered well.
27. 19M.1.HL.TZ0.11
State the output from the binary tree using postorder traversal.
[2]
Markscheme
Award [2] for completely correct answer and [1] for any 3 numbers in correct
order.
Postorder traversal: 76 75 79 70 68 72 83
Examiners report
Most candidates answered this question reasonably well.
28. 19M.1.HL.TZ0.12
Outline why a binary tree would be a good choice of data structure for maintaining an address
book.
[2]
Markscheme
Award [2 max].
Time efficient searching / traversing for a contact in an address book;
Each iteration / comparison allows the size of the search to be reduced (by
skipping about half of the remaining contacts);
Fast/easy addition / removal of contacts in an address book;
Quick search for the leaf node / empty node where a new contact can be placed /
for the node containing the contact to be deleted;
Contacts can be listed / output in alphabetical order/ fast sorting;
using inorder traversal;
Examiners report
A few candidates provided too vague, out-of-context answers.
29. 19M.1.HL.TZ0.17
A two-dimensional array 𝐶𝑈𝑆𝑇𝑂𝑀𝐸𝑅𝑆 [ ] is used to store customer details for a mail order
company such that each row of the array represents a customer record and each column
represents a specific field. The fields currently in use are: LASTNAME, FIRSTNAME,
ADDRESS1, ADDRESS2, ADDRESS3, CITY, POSTCODE.
(a) Construct the pseudocode that will find how many customers live in the city of Cardiff and
display the results.
[5]
Markscheme
Award [5 max].
Initialization of TOTAL before loop and output of result after loop;
Use of any loop with correct limits;
Correct row and column subscripts of two-dimensional array;
Correct comparison in if statement;
Totalling within if statement, if statement inside loop;
Note to examiners: Do not accept flowcharts.
Example algorithm 1:
SEARCH = "Cardiff"
TOTAL = 0
Examiners report
Those candidates who are proficient in programming easily got full marks. The
others did not complete the exercise or completed it incorrectly.
The company wishes to print a number of mailing labels, such as the one shown below, that will
go to all customers called 𝐽𝑜𝑛𝑒𝑠 who live in 𝐶𝑎𝑟𝑑𝑖𝑓𝑓.
(b) Construct an algorithm that will enable the company to print the mailing labels for all
customers called Jones who live in Cardiff.
[5]
Markscheme
Award [5 max].
Use of any loop with correct limits;
Correct row and column subscripts of two-dimensional array;
Correct comparison in if statement
Output of all row elements(fields)
Output correctly formatted
Note to examiners: Accept flowcharts.
Example algorithm 1:
SEARCH1 = "Jones"
SEARCH2 = "Cardiff"
loop COUNTER from 0 to 511
if CUSTOMERS[COUNTER][0] = SEARCH1 then
if CUSTOMERS[COUNTER][5] = SEARCH2 then
output CUSTOMERS[COUNTER][1] " " CUSTOMERS[COUNTER][0]
output CUSTOMERS[COUNTER][2]
output CUSTOMERS[COUNTER][3]
output CUSTOMERS[COUNTER][4]
output CUSTOMERS[COUNTER][5]
output CUSTOMERS[COUNTER][6]
end if
end if
end loop
Example algorithm 2:
R=0
loop while R <= 511
if CUSTOMERS[R][0]=="Jones" and CUSTOMERS[R][5]== "Cardiff"
then
output CUSTOMERS[R][1], CUSTOMERS[R][0]
loop K from 2 to 6
output CUSTOMERS[R][K]
end loop
end if
R=R+1
end loop
Note to examiners:
Since “Jones” can be either a first or last name, accept
CUSTOMERS[COUNT][1] == SEARCH1
and the first output line
output CUSTOMERS[COUNT][0], CUSTOMERS[COUNT][1]
A singly linked list has been created including the following surnames; Bale, Cousens, Davies,
Pugh, Williams.
(c) Explain the steps to insert “Jones” into this singly linked list. You may draw a labelled diagram
in your answer.
[5]
Markscheme
Award [5 max].
Accept correct answers given as diagrams or written in text applying the following
marking points:
Award [5 max] if candidate explained the steps to insert “Jones” into sorted list at
correct place.
Award [1] for each of the following steps, up to [5]
Create a new node with data field Jones and pointer field;
Start searching from the beginning of the list;
Find the location/position where the new node is to be inserted (Jones to be
inserted after Davies);
Set the pointer in the new node (containing Jones) to the pointer in the node
containing Davies (to point to the node containing Pugh);
Set the pointer in the node containing Davies to point to the new node (Jones);
Award [3 max] if candidate explained only the steps to insert “Jones” at the end of
the list.
Award [1] for each of the following steps
Create a new node with data field Jones and pointer field NIL;
Start searching from the beginning of the list to find the last node (Williams);
Set the pointer in the last node (containing Williams) to point to the new node
(Jones);
Award [3 max] if candidate explained only the steps to insert “Jones” at the
beginning of the list.
Award [1] for each of the following steps, up to [3]
Create a new node with data field Jones and pointer field;
Set the pointer in the new node (containing Jones) to the external pointer (which
points to the beginning of the list/to the first node in the list (Bale));
Set the external pointer to point to the new node (Jones);
Examiners report
Part (c) seems to have split the cohort; strong candidates often responded with
full and correct answers, however there were many responses that were
completely wrong.
(d) Outline one example of where a circular linked list would be used in preference to a linear
linked list.
[2]
Markscheme
Award [2 max].
Award marks for the use of circular lists (rather than linked lists) in an application
(accept examples);
in which any node can be a starting point / which traverses the whole list
by starting from any point;
to repeatedly go around the list;
Used to allow multiple applications to run in a PC;
The operating system cycles through each one in time giving each a slice of time
to execute;
Used for the implementation of a (circular) queue;
The end of the queue points to the beginning, eliminating the need to maintain
both front and rear pointers;
Used in multiplayer gaming environment;
The OS cycles through one player at a time using time slicing;
A media playlist that repeats (endlessly);
The last song (node) points to the first song;
Examiners report
Not many candidates were able to outline a good example of the use of a circular
list in preference to a linear linked list in Part(d).
30. 18N.1.HL.TZ0.6
Explain the importance of the method isEmpty() when constructing an algorithm which performs
operations on a stack data structure.
[3]
Markscheme
Award [3 max].
Method isEmpty() returns True if there are no elements on the stack, False
otherwise;
It is important to call this method in logical expression/condition in algorithm
constructs such as branches and loops (if/while);
Before popping an element from the stack / popStack();
To prevent errors/stack underflow/program crash;
31. 18N.1.HL.TZ0.11
The names of vegetables must be always held in alphabetical order in a list in the main
memory.
The application program should allow insertion and deletion of the names of vegetables from this
list.
(a) Compare the use of a dynamic linked list for holding these names of vegetables with a static
one-dimensional array.
[3]
Markscheme
Award [1] for each comparison, up to [3 max].
The size of the dynamic list does not have to be predetermined as in an array;
The size of the dynamic list is not fixed whilst the size of an array is always fixed;
If names are sorted they can be added/deleted (more easily) by changing the
pointers without having to shuffle the names;
As records can be dynamically added/deleted the memory is better used because
there are no wasted / missing spaces as in an array;
[2]
Markscheme
Award [1] for a node containing two fields / data(name) and link (pointer) to the
next node and [1] for showing an external pointer pointing to the first vegetable on
the list, and null pointer in the last node, and pointers which link the nodes in
alphabetical order up to [2 max].
(c.i) List the steps required to insert cabbage into the linked list.
[4]
Markscheme
Award [1] for each step identified up to [4 max].
Create a new node containing cabbage;
Traverse the list (from the beginning) to find the place to insert a new node;
Cabbage should be inserted before lettuce and after asparagus;
The pointer in new (cabbage) node should be set to point to the node that is
before the insertion point / lettuce;
The pointer in node before insertion point / asparagus / should now point to the
new node / cabbage;
Note: award marks for clearly labelled diagrams in candidates’ answers.
(c.ii) Explain why deleting the first node in this list is different to deleting other nodes.
[2]
Markscheme
Award [1] for identifying a reason why deleting the first node is different to
deleting other nodes and [1] for an expansion up to [2 max].
External pointer (First) must be changed/only in situation when deleting the
beginning node the external pointer must be changed;
And set to the pointer in the link field of the first node (Asparagus) which points to
the second node/Lettuce;
(d) State the dynamic data structure suitable for maintaining this list of vegetables which will
allow faster searching for a given vegetable name.
[1]
Markscheme
Award [1 max].
Binary tree;
Sketch the data structure suggested in part (d) containing the vegetable names sorted in
alphabetical order.
[3]
Markscheme
Award [3 max].
Award [1] for clearly a binary tree and the root is Potato.
Award [1] for the correct left subtree.
Award [1] for the correct right subtree.
32. 18N.1.HL.TZ0.12
The following method, swap(A,B) is written to exchange the values of variables A and B.
swap(A,B)
TEMP = A
B = TEMP
A=B
end swap
(a.i) Assume A = 3 and B = 5.
[1]
Markscheme
Award [1 max].
A = 3 and B = 3;
(a.ii) Suggest how the algorithm used in method swap() would need to be modified to
successfully exchange the values of variables A and B.
[2]
Markscheme
Award [1] for identifying a reason why the algorithm may not work and [1] for
suggesting a solution up to [2 max].
The algorithm does not correctly swap the values because the value of B is
overwritten/lost in the second line of the algorithm;
To obtain the correct result the line B = TEMP should be swapped with the line A
= B / the order of statements should be changed as follows:
TEMP = A
A=B
B = TEMP
Method swapRows(MAT,K,L) swaps the elements of two rows (row K and row L) in the
two‑dimensional array MAT.
For example,
(b) Use pseudocode to construct an algorithm for the method swapRows().
[4]
Markscheme
Award [4 max].
Award [1] for the loop changing column indexes.
Award [1] for the use of temporary variable.
Award [1] for the correct order of statements within the loop.
Award [1] for correct reference to elements of MAT.
Example 1:
swapRows(MAT, K, L)
loop for C from 0 to 3
T = MAT[K][C]
MAT[K][C] = MAT[L][C]
MAT[L][C] = T
end loop
end swapRows
Example 2:
Award [1] for the loop changing column indexes.
Award [1] for the using/calling method swap().
Award [1], [1] for each correct parameter in swap method call.
swapRows(MAT, R1, R2)
loop for C from 0 to 3
swap (MAT[R1][C], MAT[R2][C])
end loop
end swapRows
A game consists of four rounds. In each round a player can score up to 100 points.
The data about the game is sorted in alphabetical order of names and stored in the memory as
follows
Where
PLAYERS is a one-dimensional array holding names of players (currently sorted in alphabetical
order).
ROUNDS is a two-dimensional array holding players’ scores.
TOTALS is a one-dimensional array holding total scores.
For example,
PLAYER[1] is Boris. The total number of points he scored is 180 and this can be found in
TOTALS[1].
Boris scored 40 points in the first round which can be found in ROUNDS[1][0].
The value stored in ROUNDS[1][2] is 50 which means that Boris scored 50 points in the third
round.
[1]
Markscheme
Award [1 max].
105;
(c.ii) State where Hugh’s score in the fourth round can be found.
[1]
Markscheme
Award [1 max].
ROUNDS[2][3];
(d) All the data stored in memory should be sorted in ascending order of total score using
selection sort.
For example, after sorting, the data given opposite will be held in memory as follows
Construct an algorithm that will sort all the data in ascending order.
In your solution you should call methods swap() and swapRows() given in part (a) and part (b).
[6]
Markscheme
Award [6 max].
Award [1] for the correct outer loop (loops through the array TOTALS).
Award [2 max] for correct determination of MINIM / the position of smallest
element in part of array TOTALS (range should be from J + 1 to 5), [1] for minor
error.
Award [1] for correct condition / to check whether swaps are needed or not.
Award [1] for correct swap of elements in array TOTALS.
Award [1] for correct swap of elements in array PLAYERS.
Award [1] for correct swap of rows in two-dimensional array ROUNDS.
Example answer:
loop for J from 0 to 5
MINIM = J
loop for I from J + 1 to 5
if TOTALS[I] < TOTALS[MINIM]:
MINIM = I
end if
end loop
if MINIM != J
swap(TOTALS[MINIM],TOTALS[J])
swap(PLAYERS[MINIM], PLAYERS [J])
swapRows(ROUNDS, MINIM, J)
end if
end loop
33. 18M.1.HL.TZ0.7
Define the term recursion.
[1]
Markscheme
Process/method/ procedure/ subroutine/ function/ algorithm that calls itself;
34. 18M.1.HL.TZ0.8
[2]
Markscheme
Award [2].
FIFO data structure;
Items can be added only to one end (rear/tail) and removed from the other end
(front/head);
35. 18M.1.HL.TZ0.9
Compare the use of a linked list with an array to store and process the daily sales in a business.
[3]
Markscheme
Award [3].
Award [1] for size comparison.
Award [1] for access comparison.
Award [1] for relation to the given scenario.
Example:
Size/length of a static array is predetermined/fixed / size of a linked list can be
changed / size of a linked list depends only on memory available;
Linked list can be expanded to suit the daily sales;
Each item in a static array can be directly accessed whilst access to the items in a
linked list is sequential;
And searching for the given item in the linked list is slower /an item in the linked
list cannot be searched for using binary search;
36. 18M.1.HL.TZ0.13
The names of students attending a science fair were recorded in a stack data structure as each
one arrived.
The first item stored in the stack was “Sophie”.
(a) Construct the pseudocode that will search the stack for a specific name, and output its
position in the stack. You may assume that all names in the stack are unique.
[5]
Markscheme
Award [5 max] as follows:
Example answer 1:
searchName(NAME, STACK)
DEPTH = 0
NAMEDEPTH = -1
while not STACK.isEmpty() do
X = STACK.pop()
if X == NAME
then NAMEDEPTH=DEPTH
DEPTH = DEPTH + 1
end while
if NAMEDEPTH == -1
then output(NAME + ’not found’)
else output(NAMEDEPTH)
endif
end searchName
Award [1] for initialization.
Award [1] for a correct while/until loop.
Award [1] for correct comparison and assignment.
Award [1] for updating and outputting correct position of NAME on the
stack(NAMEDEPTH)
Award [1] for use of stack methods (pop() and isEmpty())
Example answer 2:
NAME=input()
CSTK = STACK.copy() // must make a real copy,
//any attempt to make a copy of stack is acceptable
DEPTH = 0
SEARCHING = true
while SEARCHING and not CSTK.isEmpty() do
if NAME == CSTK.pop()
then
SEARCHING = false
else
DEPTH = DEPTH + 1
end if
endwhile
if not SEARCHING
then output(DEPTH)
else output NAME + " not found"
end if
Award [1] for initialization.
Award [1] for a correct while/until loop (even if flag is missing).
Award [1] for correct comparison and assignment.
Award [1] for incrementing and outputting correct position of NAME (DEPTH).
Award [1] for use of stack methods pop() and isEmpty()).
(b) Explain the benefits of using a binary search tree, compared to a stack, when searching for a
specific item.
[3]
Markscheme
Award [3 max].
Example answer 1 (time efficiency):
The data in the binary search tree(BST) is ordered;
Such that as each node is checked for the item, half of the remaining nodes are
ignored;
But each element in the stack has to be checked;
Which, for large data sets, may be inefficient compared to the BST;
Example answer 2 (memory efficiency):
Each element on the stack has to be popped off/removed from the stack to be
checked for the searched item;
When the item is found the stack will be empty/stack contents will be changed;
When an element in the BST is checked for the item it is not removed from the
BST;
So there is no need to create an additional copy of the BST (but a real copy of the
stack must be created which for large data sets may be inefficient);
(c) If the tree is populated with the data from the stack, the first item popped off will become the
root. For each subsequent item popped from the stack, a recursive procedure is followed
until the item is correctly placed in the tree.
[4]
Markscheme
Award [4 max].
Example answer:
The (next) stack item is (placed into a new node and) compared (alphabetically)
to the root;
If the root is empty it would be placed here (and this recursive procedure
terminates);
Else, depending upon the comparison, it would look to the node to the left or right
and the (recursive) procedure calls itself again (with the new root);
If it is lower than the root, then the left child of the root becomes the new root;
If it is higher than the root, then the right child of the root becomes the new root;
Note: Marks should also be awarded for an algorithm constructed in pseudocode.
(d) By considering only the data visible in the stack shown above, sketch the binary search tree
that has been created from the items removed from the stack.
[3]
Markscheme
Award [3].
Award marks as follows:
Clearly a binary tree;
Correct root;
All values correct;
37. 18M.1.HL.TZ0.15
A transport authority is investigating how many people use a certain direct train route.
At the end of each day, the total number of passengers who travelled on this route is stored in a
collection, PASSENGERS.
The first item was written to the collection on Monday 1st May 2017.
The next items, collected on Tuesday and Wednesday, were added like this:
Data for 30 complete weeks was added to the collection.
(a) Construct pseudocode that will read PASSENGERS into the two-dimensional array,
2D_ARRAY.
[4]
Markscheme
Award [4] as follows.
Example answer 1:
Assumes that an array of sufficient size is declared (2D_ARRAY[][]) and
PASSENGERS contains valid data for all 7 days in each of 30 weeks.
PASSENGERS.resetNext()
N=0
loop while PASSENGERS.hasNext()
//accept not PASSENGERS.isEMPTY()
//accept N<PASSENGERS.length()
WEEK = N div 7
DAY = N mod 7
2D_ARRAY[WEEK][DAY] = PASSENGERS.getData() //
PASSENGERS.getNext()
N=N+1
end loop
Award [1] for while loop.
Award [1] for correct calculation of row index(WEEK).
Award [1] for correct calculation of column index(DAY).
Award [1] for correct array subscripts.
Award [1] for correct use of collection methods.
Example answer 2:
Assumes that an array of a sufficient size is declared (2D_ARRAY[][]) and
PASSENGERS contain valid data for all 7 days in each of 30 weeks.
PASSENGERS.resetNext()
loop for WEEK from 0 to 29
loop for DAY from 0 to 6
2D_ARRAY[WEEK][DAY] =
PASSENGERS.getNext()//PASSENGERS.getData()
end loop
end loop
Award [1] for nested loops.
Award [1] for loops that generate the right output (correctly read
PASSENGERS into 2D_ARRAY).
Award [1] for assignment into correct array location.
Award [1] for correct use of collection methods.
(b) Construct the pseudocode for the procedure total, that takes as input a column number of
this two-dimensional array and returns the sum of the elements in that column.
[4]
Markscheme
total (N)
// if N (column number) is not passed as an input parameter then
// assignment must appear in pseudocode, for example, N = input()
SUM = 0
loop for WEEK from 0 to 29
SUM = SUM + 2D_ARRAY[WEEK][N]
end loop
return SUM
end total
Award [1] for assigning the input to a variable / passing the value of N.
Award [1] for initializing and returning/outputting SUM.
Award [1] for correct loop.
Award [1] for correct addition of each term to SUM. (Note: The array position
must be completely correct with the input column and the varied row.)
(c) The transport authority wishes to know how many passengers, on average, travel on each
day of the week.
Using the procedure total construct the pseudocode to output the day of the week with the
highest average number of passengers, and the value of this average.
You should make use of the sub procedure convert() which converts the numbers 0 to 6 into
days of the week, for example convert(1) will return “Tuesday”.
[3]
Markscheme
MAXAV = 0
MAXDAY = ""
loop for DAY from 0 to 6
if total(DAY)/30 > MAXAV
MAXAV = total(DAY)/30
MAXDAY = convert(DAY)
end if
end loop
output MAXAV,MAXDAY
Award [1] for correct loop.
Award [1] for use of method total() when calculating the average number of
passengers.
Award [1] for initializing, updating and outputting/returning MAXAV and MAXDAY.
(d) The transport authority stores details about the ticket prices in a one-dimensional array,
FEES, where FEES[0] contains the price of a ticket for Monday to Friday, while
FEES[1] contains the price of a ticket for Saturday and Sunday.
The procedure salesCalculate() takes as input the column and row indices that define two
specific days during the 30 weeks, and outputs the total amount of money generated from
ticket sales between those two days (inclusive).
[7]
Markscheme
salesCalculate(2D_ARRAY, A, B, X, Y)
// A,B are row & column of first day,
// X,Y are row & column of last day.
TOTAL = 0
output TOTAL
end salesCalculate
Award [7 max].
Award [1] for initializing, updating and outputting TOTAL.
Award [1] for nested loops.
Award [1] for correct calculation of TOTAL in row/week A (column
subscripts/days/ in 2D_ARRAY must be in range B to 6).
Award [1] for correct calculation of TOTAL in row/week X (column
subscripts/days/ in 2D_ARRAY must be in range 0 to Y).
Award [1] for correct calculation of TOTAL in rows/weeks from A + 1 to X – 1
(column subscripts/days/ in 2D_ARRAY must be in range 0 to 6).
Award [1] if evident that the number of days to be included in calculating total
amount is different for weeks A + 1 to X – 1, week A and X (three different cases).
Award [2], [1] for checking for weekdays / weekend and [1] for using correct
subscript in FEE (0 for weekdays, 1 for weekend).
38. 17N.1.HL.TZ0.13
[2]
Markscheme
Award up to [2 max].
Each node contains data and also a link to other nodes;
Links between nodes are implemented by pointers (a pointer references a
location in memory or holds a memory address);
List size is not fixed / predetermined;
Consider the following doubly linked list which holds the names of flowers in alphabetical order.
(b) Explain how “Primrose” could be inserted into this doubly linked list. You should draw a
labelled diagram in your answer.
[6]
Markscheme
Award up to [6 max] as follows. (There are 7 marking points)
[1] create new node;
[1] instantiation of values and pointers in new node;
[1] state where the search starts from;
[1] how to detect position for insertion;
[1] update pointers in new node;
[1] update pointers from the node at the insertion point, to the new node;
[1] update external pointers;
Remark: Some answers may just use illustrations alone, or very minimal
explanations: see note below;
Create a new node (with pointer NEWNODE) with data field Primrose and two
pointer fields (next and previous), to be inserted;
Perform a linear search, either from the beginning or end of the list (using pointers
FIRST and LAST, on the alphabetically order list;
The location/position of insertion, is found by comparing nodes (Primrose to be
inserted after Lavender, LOCATION points to Lavender) (Accept any description
to that effect);
(At the end of this phase, the situation looks as in Figure 1)
Figure 1
Then, continue by setting the “next” field/pointer in the newly created node to
NULL;
Set the “previous” pointer in the newly created node to the current LAST / to point
to Lavender/ to point to the node detected by LOCATION;
Change/Set/Update the Lavender’s “next” pointer to point to the new node / to link
with the NEWNODE pointer (delete NULL in the field and link to the existing
NEWNODE pointer);
Update the LAST pointer to point to the newly created node;
Eventually the final doubly linked list looks like this (Figure 2);
Figure 2
Note: Award [4 max] for responses that return one or more drawings without any
explanation at all, for evidence of these features:
[1] Evidence of creation of an initial new node for Primrose out of the list;
[1] The order of nodes Aster/Camellia/Lavender/Primrose is eventually correct;
[1] The two unidirectional links between Lavender and Primrose are (eventually)
correctly displayed, from-to the appropriate fields;
[1] LAST points correctly to the appropriate field in the new node Primrose, and
NULL fills the last field of the new node;
Consider the two stacks: FLOWERS and FRUITS.
(c)
[4]
Markscheme
Award [1] for each one in the correct order.
Apple;
Broom;
Camellia;
Day Lily;
Note: Solution for the Spanish version (in this order):
Aster; Camelia; Lavanda; Lirio;
(d) A third stack, FLOFRU, is needed. It should contain all the data from FLOWERS and
FRUITS and will store it as shown below
Describe how the FLOFRU stack could be created.
[3]
Markscheme
Award marks as follows up to [3 max].
Example answer 1
Create an empty stack (FLOFRU);
pop all elements from FRUITS and push them onto FLOFRU;
Then pop all elements from FLOWERS and push them onto FLOFRU;
Example answer 2
Create an empty stack (FLOFRU);
While FRUITS is not empty
pop an element from FRUITS and push it onto FLOFRU;
While FLOWERS is not empty
pop an element from FLOWERS and push it onto FLOFRU;
Note: Award [2 max] for generic descriptions that do not use appropriate
terminology on data structures and their operations.
39. 17N.1.HL.TZ0.6
mystery(N)
if (N > 0) AND (N mod 2 = 0) then
mystery(N−2)
end if
output N
end mystery
[1]
Markscheme
5;
[3]
Markscheme
Award up to [3] as follows:
[3] for fully correct response (sequence of output) “0;2;4”;
[2] for response (sequence) “4;2;0” (all elements are correct, but they are in
inverse order);
[1] for response ”0” (only base case is correct);
OR
“0;2” (incomplete output, but initially correct, and with correct order);
OR
“–2;0;2;4”,“0;2;4;6” (correct sequence immersed in some unnecessary and
incorrect context);
[0] in all other cases (e.g. responses “2”, “4”, “2;0”, “2;4”, “4;2”);
0
2
4
(c) Construct an iterative algorithm for the method mystery() , which uses a single while loop
instead of recursion.
[4]
Markscheme
Example answer 1
Award marks as follows up to [4 max]. (There are 5 marking points);
Award [1] for determining whether N is odd/even;
Award [1] for correctly initializing and changing the value of the loop
controlling variable (K);
Award [1] for the correct condition in the while loop;
Award [1] for output within the loop for an even N;
Award [1] for output after the loop for an odd N;
mystery(N)
if N mod 2 = 0 then
K=0
loop while K <= N
output K
K=K+2
end loop
else
output N
end if
end mystery
Example answer 2
Award marks as follows up to [4 max]. (There are 5 marking points);
Award [1] for determining whether N is odd/even;
Award [1] for correctly initializing and changing the value of the loop controlling
variable (K);
Award [1] for the correct condition in while loop (note K < N);
Award [1] for output within the loop for an even N;
Award [1] for outputting N after the loop;
mystery(N)
K=0
loop while (K < N) AND (N mod 2 = 0)
output K
K=K+2
end loop
output N
end mystery
Note: No marks for any attempt of program that contains recursive calls.
40. 17N.1.HL.TZ0.14
The value −1 is stored in MAT at position [4][2]. The position [4][2] means row 4 and column 2.
[1]
Markscheme
36;
[1]
Markscheme
7;
A two-dimensional array in which most of the elements are zero is called a sparse matrix. A
sparse matrix can be compressed by storing only non-zero elements using three
one‑dimensional arrays.
The first array, VALUES, stores all non-zero elements taken from the sparse matrix in
row‑major order (left-to-right then top-to-bottom order).
The length of the array VALUES is equal to the number of non-zero elements in the sparse
matrix. For the sparse matrix above, MAT, the array VALUES is:
The second array is ROWC. ROWC[i] stores the number of non-zero elements, from row 0 to
row i of the sparse matrix, inclusive.
The length of ROWC is equal to the number of rows in the sparse matrix. For MAT the array
ROWC is:
For example, ROWC[2] stores 3 because in MAT there are three non-zero elements from row
0 to row 2, inclusive.
The third array, COL, stores the column index for each non-zero element in the sparse matrix.
COL[i] stores the sparse matrix column index for the non-zero element stored in VALUES[i]. For
MAT the array COL is:
(c) Construct an algorithm that compresses a 6 × 6 two-dimensional array, such as MAT, into the
three one-dimensional arrays described in the resource. You may assume that the 6 × 6
array is inputted and all three one-dimensional arrays are initialized.
[6]
Markscheme
Award marks as follows up to [6 max]. (There are 7 marking points)
Award [1] for initialization and correct changes of K (index/position in
arrays VALUES and COL);
Award [1] for initialization and correct changes of COUNT (counts non-zero
elements);
Award [1] for correct conditions in “row” loop;
Award [1] for correct conditions in “column” loop;
Award [1] for placing non-zero element at correct position in array VALUES;
Award [1] for placing the “column” index of the non-zero element at correct
position in array COL;
Award [1] for placing COUNT at correct position in array ROWC;
COUNT = 0
K=0
loop for I from 0 to 5
loop for J from 0 to 5
if MAT[I][J]! = 0 then
VALUES[K] = MAT[I][J]
COL[K] = J
K=K+1
COUNT = COUNT + 1
end if
end loop
ROWC[I] = COUNT
end loop
Consider the following three arrays. They hold the compressed contents of a 7 × 7 sparse
matrix, 𝐵𝐼𝐺𝑀𝐴𝑇.
(d) For a given column, C, in BIGMAT, outline how it could be determined that this column
contains no non-zero elements.
[2]
Markscheme
Award up to [2 max].
Example answer 1
Array COL should be searched for (value) C;
If (value) C is not found in array COL then this column (the column whose index in
BIGMAT is C) holds only zeros;
Example answer 2
If the number of occurrences of (value) C in array COL;
Equals zero then this column holds only zeros;
Example answer 3: Award [1 only].
If COL[C] = COL[C–1], then the column with index C in BIGMAT contains no
non-zero-elements;
(Accept words to that effect: “if the difference between COL[C] and COL[C-1] is
zero, then...”);
[1]
Markscheme
1;
(f.i) State the index in 𝑉𝐴𝐿𝑈𝐸𝑆 of the first non-zero element in row 5 of 𝐵𝐼𝐺𝑀𝐴𝑇.
[1]
Markscheme
5;
(f.i) State the index in VALUES of the first non-zero element in row 5 of BIGMAT.
[1]
Markscheme
5;
(f.ii) For a given row, R in BIGMAT, determine the range of indexes in VALUES where non-zero
elements in row R of BIGMAT are placed. You may assume that there is at least one
non-zero element in row R.
[3]
Markscheme
Award marks as follows up to [3 max].
Award [1] for realizing that the range should be determined differently for the first
row (when row index R is 0) OR correct range when row index is 0;
Award [1] for correct first index in range (when row index R is not 0);
Award [1] for correct last index in range;
If row index R is equal to 0 then the range is from 0 to ROWC[0]-1 ;
If row index R is not equal to 0 then the range is from ROWC[R-1];
To ROWC[R]-1;
Note: Award [2 max] for a correct calculation of the indexes, but no unifying
expression showing how they have been calculated is given).