Unit 2 Cycle 2 Day 26: Loop Algorithm: Palindrome Check
Share
Loop Algorithm: Palindrome Check
Section Mixed — Review: Loops and Strings
Key Concept
A palindrome check algorithm compares characters from both ends of a string moving inward. The standard approach uses two indices: one starting at 0 and one at length() - 1, comparing charAt(left) to charAt(right) and moving them closer until they meet or cross. If any pair does not match, the string is not a palindrome. The AP exam may test this with a complete implementation to trace, or with a broken implementation to identify the error. Consider edge cases: empty strings, single characters, and strings with even versus odd lengths.
Consider the following method.
What does check("abba") return?
Answer: (A) true
"abba": left=0(a), right=3(a): match, continue. left=1(b), right=2(b): match, continue. left=2, right=1: 2 < 1 is false, loop ends. Return true. "abba" is a palindrome.
Why Not the Others?
(B) All character pairs match (a==a, b==b), so the method never returns false.
(C) All indices are within bounds. The two-pointer approach stays within the string.
(D) left increases and right decreases each iteration. They converge and the loop ends.
Common Mistake
The two-pointer palindrome check compares characters from both ends, moving inward. It returns false as soon as a mismatch is found, or true if all pairs match.
AP Exam Tip
Two-pointer algorithms are common on the AP exam. Recognize the pattern: one pointer starts at the beginning, one at the end, and they move toward each other.