Worked solution from the Programming Paper 2 Problem-solving and Programming booklet, Part 3 of 3.
Compare the first character with the last, the second with the second last, and so on. Only half the string needs checking. Change both characters to the same case before comparing.
FUNCTION IsPalindrome(InString : STRING) RETURNS BOOLEAN
DECLARE IsPal : BOOLEAN
DECLARE Index, Num : INTEGER
DECLARE CharA, CharB : CHAR
IsPal ← TRUE
Index ← 1
Num ← INT(LENGTH(InString) / 2)
WHILE Index <= Num AND IsPal = TRUE
CharA ← MID(InString, Index, 1)
CharB ← MID(InString, LENGTH(InString) - Index + 1, 1)
IF UCASE(CharA) <> UCASE(CharB) THEN
IsPal ← FALSE
ENDIF
Index ← Index + 1
ENDWHILE
RETURN IsPal
ENDFUNCTIONFunction header with the string parameter, ending and BOOLEAN return type [1]
Work out the number of pairs to compare (half the length) [1]
A loop over half (or all) of the string [1]
Extract the two characters to compare (or build the reversed string) [1]
Convert both characters to the same case, for example UCASE [1]
Test for a mismatch inside the loop (or compare with the reversed string after it) [1]
Return TRUE or FALSE correctly in both cases [1]
Follow the flowchart: A sets OutString, B ends the loop at the end of the string, C tests for a space, D adds a non-space character to OutString.
| Label | Text |
|---|---|
| A | Set OutString to "" |
| B | Is Index > LENGTH(InString)? |
| C | Is MID(InString, Index, 1) = " "? |
| D | Set OutString to OutString & MID(InString, Index, 1) |
| E | Set Index to Index + 1 |
| F | YES |
| G | NO |
Label B correct [1]
Label C correct [1]
Label D correct [1]
F = YES and G = NO (the space test on C must be sensible) [1]
▶ Whole paper
Video solution of the whole paper · by CS BY AQIB KHAN. Tap the picture to open it on YouTube.
Solutions follow the official Cambridge mark schemes; marks are shown in grey. Videos are from other YouTube channels. Paper codes read component / series / year: M/J = May/June, O/N = October/November. Past-paper questions © UCLES, reproduced for classroom practice.