The problem, in one line. Decide whether a sentence reads the same backwards once you throw away everything except letters and digits and ignore capitals. LeetCode 125.
The tell. The question compares the first item with the last, then the second with the second to last. Whenever a check pairs up the two ends, put one marker on each end and walk them toward each other.
The wrong first idea
Build a cleaned copy, reverse it, and compare.
t = [c.lower() for c in s if c.isalnum()]
return t == t[::-1]
This is correct and still O(n). The cost is memory: two extra lists as long as the sentence. The question only ever asks “does this end match that end?”, so no copy is needed. The no-copy version is the usual follow-up.
The invariant
Put a marker on each end. Skip any marker that sits on punctuation or a space. Compare the two letters, then move both inward.
flowchart LR A["ab, Ba<br/>i=0 a, j=5 a<br/>equal"] --> B["i=1 b, j=4 B<br/>equal once lowercased"] B --> C["i skips ',' and ' '<br/>markers cross<br/>True"]
The sentence that stays true every step: everything outside the two markers has already been matched. When the markers cross, nothing is left to disagree.
The solution
def is_palindrome(s):
i, j = 0, len(s) - 1
while i < j:
if not s[i].isalnum():
i += 1
elif not s[j].isalnum():
j -= 1
elif s[i].lower() != s[j].lower(): # compare the two ends, then close in
return False
else:
i += 1
j -= 1
return True
print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("race a car"))
print(is_palindrome(" "))
True
False
True
func isPalindrome(s string) bool {
r := []rune(s)
i, j := 0, len(r)-1
for i < j {
if !isAlnum(r[i]) {
i++
} else if !isAlnum(r[j]) {
j--
} else if unicode.ToLower(r[i]) != unicode.ToLower(r[j]) { // compare the two ends, then close in
return false
} else {
i++
j--
}
}
return true
}
func isAlnum(c rune) bool { return unicode.IsLetter(c) || unicode.IsDigit(c) }
Same calls print true false true on one line.
Complexity
- Time O(n): each marker only moves inward, so every character is looked at once.
- Space O(1): two integers, no cleaned copy.
Traps
- Skipping with a bare
whileand noi < jguard. On.,the marker runs off the end and raises an index error. - Keeping only letters with
isalpha. The input0Pthen looks like a palindrome, but it is not, because0andPdiffer. - Forgetting to lowercase.
Aais a palindrome here, and a plain==on the two characters says it is not.
Next in the ladder
Two Sum II, Input Array Is Sorted keeps the two inward markers, but they now move on a sum instead of a match, and the sorted order tells you which marker to move.