ITPEC FE Subject B October 2024 Question 12

From the answer group below, select the correct combination of answers to be inserted into A and B in the program. Here, the array index starts at 1.

The function isPalindrome determines whether the character array s given as argument is a palindrome. Palindromes are words when read backward will still be the same such as “noon” and “madam.”
If character array s is a palindrome, it returns the value true and if not, the function returns false.

The table lists examples of s given to the function isPalindrome and the return values. In the program, areas outside of the arrays must not be referenced.

Table Examples of s given to the function isPalindrome and the return values

sReturn value
{"n", "o", "o", "n"}true
{"n", "i", "g", "h", "t"}false
{"m", "a", "d", "a", "m"}true
{"s", "i", "r"}false
[Program]
○ boolean: isPalindrome(character []: s)
integer: left ← 1
integer: right ← the number of elements in s
boolean: ok ← true
while (left < right)
if (A)
left ← left + 1
B
else
ok ← false
break
endif
endwhile
return ok

Answer group

OptionAB

Explanation

A: s[left] = s[right], B: right ← right - 1 — two indexes start at the two ends and move toward each other while the characters match.

left starts at 1 and right at the last element. The else branch sets ok to false, so A must be the test for a matching pair. When the pair matches, both ends move inward: the program already does left ← left + 1, so B must move right down by 1.

Trace with {"m", "a", "d", "a", "m"}:

leftrightcomparedresult
15m and mequal, move in
24a and aequal, move in
33nothingloop ends, true

With {"s", "i", "r"} the first pair, s and r, differs, so the function returns false.

Answer (b)

Why not others:

  • •(e), (f), (g) and (h) — s[left] ≠ s[right] inverts the test: the first pair of {"n", "o", "o", "n"} is equal, so it takes the else branch and returns false for a palindrome
  • •(a) — right ← right + 1 moves right outward, so after the first matching pair s[right] is an element past the end of the array, which the description forbids
  • •(c) — right ← right + left also grows right (5 + 2 = 7 for "madam"), again outside the array
  • •(d) — right ← right - left skips pairs: for "madam" it jumps from 5 to 5 - 2 = 3 and compares a with d, returning false for a palindrome

Key rule: In a two-pointer scan, each pointer moves one step toward the other per iteration, and the loop condition left < right stops them when they meet.

String Processing · AI-written, may contain errors

This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.