Now that we've explored the building blocks of algorithms, let's put them to work with some practical examples. One classic and engaging problem is checking if a word or phrase is a palindrome. A palindrome is a sequence that reads the same backward as forward. Think 'madam,' 'racecar,' or 'level'.
Our goal is to create an algorithm that takes a string as input and returns 'true' if it's a palindrome, and 'false' otherwise. We can approach this by comparing characters from the beginning and the end of the string, moving inwards. If we find any mismatch, it's not a palindrome.
graph TD; A[Start] --> B{Input String}; B --> C{Initialize two pointers: start=0, end=length-1}; C --> D{While start < end}; D -- True --> E{If string[start] == string[end]}; E -- True --> F{Increment start, Decrement end}; E -- False --> G[Return False]; F --> D; D -- False --> H[Return True]; G --> I[End]; H --> I;
Let's visualize this with an example: 'level'.
- We set
startto 0 (pointing to 'l') andendto 4 (pointing to the last 'l'). - 'l' equals 'l'. We increment
startto 1 and decrementendto 3. - Now
startpoints to 'e' andendpoints to 'e'. - 'e' equals 'e'. We increment
startto 2 and decrementendto 2. - The condition
start < endis no longer true. We exit the loop. - Since we completed the loop without finding any mismatches, the string is a palindrome, and we return 'true'.
Consider 'hello':
start= 0 ('h'),end= 4 ('o').- 'h' does NOT equal 'o'.
- We immediately return 'false'.
Here's how this logic can be translated into code. We'll use a function that accepts the string and returns a boolean value.
function isPalindrome(str) {
let start = 0;
let end = str.length - 1;
while (start < end) {
if (str[start] !== str[end]) {
return false;
}
start++;
end--;
}
return true;
}We can test our function with a few cases:
isPalindrome('madam') should return true.
isPalindrome('hello') should return false.
isPalindrome('a') should return true (single characters are palindromes).
isPalindrome('') should return true (an empty string is also considered a palindrome).