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- A. 4
- B. 7
- C. 6
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The string "abcabcbb" is scanned with a sliding window that keeps the longest stretch without a repeated character. The procedure below…
- Scanning "abcab dab" as a string of letters, the procedure below counts the adjacent pairs that read "ab" (both letters next to each…
- Two words are checked as anagrams by comparing letter counts. The procedure below sums the absolute differences between the letter counts…
- The minimum number of insertions or deletions needed to make the string "abcca" a palindrome is len(s) - LPS(s), where LPS is the length…
- The edit distance (Levenshtein, insert/delete/replace each cost 1) between "kitten" and "sitting" is computed by the standard table. What…
- The string " hello world " is split by the Python-style rule that runs of spaces are treated as one separator and empty pieces are…