Problem
Write a function isPalindrome(string $s): bool that returns true for inputs like:
"racecar"→ true"A man, a plan, a canal: Panama"→ true"hello"→ false
Solution
php
<?php
function isPalindrome(string $s): bool {
// Keep only letters and digits, lowercase everything
$clean = strtolower(preg_replace('/[^a-z0-9]/i', '', $s));
return $clean === strrev($clean);
}
var_dump(isPalindrome("racecar")); // true
var_dump(isPalindrome("A man, a plan, a canal: Panama")); // true
var_dump(isPalindrome("hello")); // false
Two-pointer alternative (O(1) memory, no string copy)
php
function isPalindromeTwoPointer(string $s): bool {
$s = strtolower($s);
$l = 0; $r = strlen($s) - 1;
while ($l < $r) {
while ($l < $r && !ctype_alnum($s[$l])) $l++;
while ($l < $r && !ctype_alnum($s[$r])) $r--;
if ($s[$l] !== $s[$r]) return false;
$l++; $r--;
}
return true;
}
What interviewers look for
- Edge cases — empty string is a palindrome; single char is a palindrome.
- Did you handle Unicode?
strrevreverses bytes, not characters. For Unicode usemb_str_split+array_reverse+implode. - Time/space complexity — both versions are O(n) time, but the two-pointer version uses O(1) extra space.
Unicode-safe version
php
function isPalindromeUnicode(string $s): bool {
$chars = mb_str_split(mb_strtolower($s));
$chars = array_filter($chars, fn($c) => preg_match('/[\p{L}\p{N}]/u', $c));
$clean = implode('', $chars);
return $clean === implode('', array_reverse(mb_str_split($clean)));
}
