Loading...

Section

Checking for Palindromes

Part of The Prince Academy's AI & DX engineering stack.

Follow The Prince Academy Inc.

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'.

  1. We set start to 0 (pointing to 'l') and end to 4 (pointing to the last 'l').
  2. 'l' equals 'l'. We increment start to 1 and decrement end to 3.
  3. Now start points to 'e' and end points to 'e'.
  4. 'e' equals 'e'. We increment start to 2 and decrement end to 2.
  5. The condition start < end is no longer true. We exit the loop.
  6. Since we completed the loop without finding any mismatches, the string is a palindrome, and we return 'true'.

Consider 'hello':

  1. start = 0 ('h'), end = 4 ('o').
  2. 'h' does NOT equal 'o'.
  3. 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).

console.log(isPalindrome('madam'));
console.log(isPalindrome('hello'));
console.log(isPalindrome('a'));
console.log(isPalindrome(''));

This palindrome checker is a straightforward example of using iteration and conditional logic to solve a problem. It demonstrates how simple comparisons can lead to powerful algorithmic solutions.