Skip to content
DSA in JavaScript
Array & String Classics

Palindrome Check

Algorithm · Starter

Step through it: Two Pointers pattern

left
right

target = 10

Step 1 of 6

Goal: find two numbers in this sorted list that add up to 10. Trying every pair is slow. Instead, put one marker at each end of the list.

A Palindrome is a string that reads the same forwards and backwards. This means that the second half of the string is the reverse of the first half.

Examples

The following are palindromes (thus would return TRUE):

- "a"
- "pop"     ->  p + o + p
- "deed"    ->  de + ed
- "kayak"   ->  ka + y + ak
- "racecar" ->  rac + e + car

The following are NOT palindromes (thus would return FALSE):

- "rad"
- "dodo"
- "polo"

Code

isPalindrome.js
/**
 * @param {string} string
 * @return {boolean}
 */

export default function isPalindrome(string) {
  let left = 0;
  let right = string.length - 1;

  while (left < right) {
    if (string[left] !== string[right]) {
      return false;
    }
    left += 1;
    right -= 1;
  }

  return true;
}

References

Practice

Spotted a mistake or something unclear? Report it on GitHub.

On this page