How to Validate a Palindrome
Tags: javascript, computerscience, tutorial, beginners
Published: 2020-08-24 21:33:48

---
title: How to Validate a Palindrome
published: true
description: Given a string `str`, can you write a method that will return `True` if is a palindrome and `False` if it is not?
tags: javascript, computerscience, tutorial, beginners
cover_image: https://storage.googleapis.com/algodailyrandomassets/curriculum/easy-strings/validate-palindrome.png
canonical_url: https://algodaily.com/challenges/validate-palindrome
---


Given a string `str`, can you write a method that will return `True` if is a palindrome and `False` if it is not? If you'll recall, a `palindrome` is defined as "a word, phrase, or sequence that reads the same backward as forward". For now, assume that we will not have input strings that contain special characters or spaces, so the following examples hold:

```js
let str = 'thisisnotapalindrome';
isPalindrome(str);
// false

str = 'racecar';
isPalindrome(str);
// true
```

For an extra challenge, try to ignore non-alphanumerical characters. The final solution that we present will handle all edge cases.

{% youtube _PfJ7dWGCAc %}

_This lesson was originally published at [https://algodaily.com](https://algodaily.com/challenges/validate-palindrome), where I maintain a technical interview course and write think-pieces for ambitious developers._


---



### True or False?



A string is defined as a palindrome if the reversal of the string is equal to the original string.

For example, “toot” is a palindrome, but “boot” is not.


**Solution:** True



---

This is a classic question, and there are multiple ways to solve this. For the sake of learning, let's cover all of them!

### Using built-in methods

<img src="https://storage.googleapis.com/algodailyrandomassets/curriculum/easy-strings/validate-palindrome.png" class="img-fluid" />

This would probably be invalid in an actual interview, but you can rely on the built-in `String` method to accomplish a quick reversal. In Javascript, you can simply call `reverse()` and in Python, you can call `[::-1]` You can then compare the reversed string to the original:



```js
function isPalindrome(str) {
	// Calling reverse function
	const reversed = str.split('').reverse().join('');

	// Checking if both strings are equal or not
	if (str == reversed) {
		return true;
	}
	return false;
}

console.log(isPalindrome('racecar'));
```

### Order

What's the order of successfully finding out if a string is a palindrome?




<ul><li>Open a while loop to perform while low is less than high</li><li>Continue until end of loop and return true</li><li>Define two variables: high and low, as 0 and (length of string - 1)</li><li>If `string[low]` does not equal `string[high]`, return false. Increment low, decrement high</li></ul>



**Solution:** 

<ol><li>Continue until end of loop and return true</li>
<li>If `string[low]` does not equal `string[high]`, return false. Increment low, decrement high</li>
<li>Open a while loop to perform while low is less than high</li>
<li>Define two variables: high and low, as 0 and (length of string - 1)</li></ol>



---



### Multiple Choice



What will the following pseudocode do to an input string?

```python
def reverse_str(str):
  start = 0
  end = len(str)-1
  str_copy = [letter for letter in str]
  while start < end:
    temp = str_copy[start]
    str_copy[start] = str_copy[end]
    str_copy[end] = temp
    start += 1
    end -= 1
  return "".join(str_copy)
```

<ul><li>Make a copy</li><li>Reverse the string</li><li>Swap the first and last letters</li><li>Infinite loop</li></ul>



**Solution:** Reverse the string



---



### With a while loop:

<img src="https://storage.googleapis.com/algodailyrandomassets/curriculum/easy-strings/validate-palindrome-1.png" class="img-fluid" />

We can cut down on the number of operations by recognizing that we don't need to do `len(str)-1` iterations. Instead of using just one pointer that simply iterates through the string from its end, why not use two?



```js
function isPalindrome(str) {
	let left = 0;
	let right = str.length - 1;
	let leftChar;
	let rightChar;

	while (left < right) {
		leftChar = str.charAt(left);
		rightChar = str.charAt(right);

		if (leftChar == rightChar) {
			left++;
			right--;
		} else {
			return false;
		}
	}

	return true;
}

console.log(isPalindrome('racecar'));
```





What we're doing above is specifying two pointers, `start` and `end`. `start` points to the beginning of the string, and `end` is a pointer to the last character. Taking the example input `racecar`, as we run through it, these are the comparisons we'll see:





```
racecar
^     ^
racecar
 ^   ^
racecar
  ^ ^
racecar
   ^
True
```



### Multiple Choice



What is the run time of the following code?

```python
def reverse_str(str):
  start = 0
  end = len(str)-1
  str_copy = [letter for letter in str]
  while start < end:
    temp = str_copy[start]
    str_copy[start] = str_copy[end]
    str_copy[end] = temp
    start += 1
    end -= 1
  return "".join(str_copy)
```



<ul><li>O(log n)</li><li>O(n)</li><li>O(n log n)</li><li>O(n^2)</li></ul>



**Solution:** O(n)



---

### Final Solution

```js
function isPalindrome(str) {
  if (!str || str === "") {
    return true;
  } else {
    let left = 0;
    let right = str.length - 1;
    let leftChar;
    let rightChar;

    while (left < right) {
      leftChar = str.charAt(left).toLowerCase();
      rightChar = str.charAt(right).toLowerCase();

      if (isAlphaNumeric(leftChar) && isAlphaNumeric(rightChar)) {
        if (leftChar == rightChar) {
          left++;
          right--;
        } else {
          return false;
        }
      } else {
        if (!isAlphaNumeric(leftChar)) {
          left++;
        }
        if (!isAlphaNumeric(rightChar)) {
          right--;
        }
      }
    }

    return true;
  }
}

function isAlphaNumeric(c) {
  if (/[^a-zA-Z0-9]/.test(c)) {
    return false;
  } else {
    return true;
  }
}

console.log(isPalindrome("A Santa Lived As a Devil At NASA"));
```

Check out more visual tutorials for [technical challenges at AlgoDaily.com](https://algodaily.com/curriculum) and try out [our daily coding problem newsletter](https://algodaily.com/challenges/daily)!