What is a palindrome ? Find the definition below from the online oxford
a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
In the example below only a word palindrome could be identified. Additional conditions would be necessary to analyze phrase or sequences
function isPalindrome($str): bool
{
$str_length = strlen($str);
$mid = round($str_length / 2);
$last_character = $str_length - 1;
for ($i = 0; $i <= $mid; $i++) {
if ($str[$i] != $str[$last_character]) {
return false;
}
$last_character--;
}
return true;
}
var_dump( isPalindrome('madam'));
var_dump( isPalindrome('nursesrun'));
var_dump( isPalindrome('davad'));
var_dump( isPalindrome('avaava'));
What is the run time complexity ?
It sounds to be O(n/2)
What is the space complexity ?
We do not allocate memory except for few variables as $i, $mid and $last_character
O(1)