ProgrammingHardTCS NQT · Accenture

A palindrome check on "racecar" uses two pointers from both ends, comparing one pair per step and stopping early on a mismatch. The procedure below counts how many character comparisons are made. What is printed?

A palindrome check on "racecar" uses two pointers from both ends, comparing one pair per step and stopping early on a mismatch. The procedure below counts how many character comparisons are made. What is printed?
l = 0; r = n - 1; comparisons = 0
while l < r
    comparisons = comparisons + 1
    if s[l] != s[r] then stop
    l = l + 1; r = r - 1
end while
Print comparisons
  1. A. 4
  2. B. 7
  3. C. 6
  4. D. 3

Correct answer: D. 3

The comparisons are made for the pairs (0,6), (1,5) and (2,4), which is 3, and the middle letter needs no pair. Testing while l is at most r makes one extra comparison, using the full length gives 7, and counting two comparisons per step gives 6.

More Pseudocode and Code Tracing questions

Exams that ask this topic