- How to Determine if a String is a Palindrome (in JavaScript)
- What is a Palindrome?
- Why does this come up in technical interviews?
- How do we implement it in code?
- Step 1: Understand how to solve the problem
- Step 2: Code it!
- Top comments (11)
- JavaScript Program to Check Whether a String is Palindrome or Not
- Example 1: Check Palindrome Using for Loop
- Example 2: Check Palindrome using built-in Functions
How to Determine if a String is a Palindrome (in JavaScript)
When it comes to solving problems in an interview setting as a software engineer, few topics come up quite as often as string manipulation. And when it comes to string manipulation, few specific concepts come up as frequently as Palindromes.
What is a Palindrome?
For those who might not know, a Palindrome according to the wikipedia page on the subject is defined as:
Though in the context of programming, a palindrome need not even be a real word (or even made up of letters.) Some examples of this type might be:
Why does this come up in technical interviews?
As you’ll see when we write our code, palindromes are a very fundamental algorithmic practice topic because they involve multiple concepts that engineers use regularly on the job, such as:
- Being able to traverse through and/or manipulate a string.
- Knowing how to set multiple pointers and use/move them within a repeating loop.
- Understanding how to take something that’s simple for a human being to do (see if a word is a palindrome) and explain that to a computer in a set of repeatable instructions.
That last one in particular is a core fundamental of problem solving in computer science. Oftentimes the easiest things for us to do as humans are the hardest things to represent simply and efficiently in code.
How do we implement it in code?
In the example we’ll be going over here, we’re going to implement a simple algorithm that will detect if a given string is (or is not) a palindrome. While this may seem like a simple task, understanding it well can give you an advantage when harder palindromic questions are asked in interviews, or when they come up in your own practice.
Think of this solution as more of a building block, or a tool that you’ll have in your toolbox to use on more difficult questions, rather than the end of all discussions on palindromes in code.
Step 1: Understand how to solve the problem
Before we code, we should first think through how we might solve this.
When we look at a word or a series of characters as humans, we recognize something as a palindrome by reading through the word up until we hit the «middle» of the word, then see that the second half of the word contains the same letters or characters as the first half.
Think of it like climbing a hill up to the top, and then noticing that the other side of the hill looks exactly the same on the way down.
Trying to do it this way in an algorithm might work if we kept track of the letters we’ve seen as we step through the string, but we’ll realize quickly that there isn’t as simple a way to tell the computer what the «middle» of the string is, conceptually, and we’ll also need to use extra space to store the first part of the string that we saved on the way there.
An easier way is to think back to that «hill» analogy I mentioned; if both sides of the string are the same on the way up and down, then couldn’t we start at both the beginning and the end of the string and work our way to the middle at the same time?
Yes we could! And that’s precisely what we’ll do in our code.
Step 2: Code it!
Let’s start by declaring our function, giving it a name and a parameter for a string to be passed in as an argument:
function isPalindrome(string) >
Now, let’s create two pointers that we’ll use to traverse the string. One will start at the beginning of the string, and the other will start at the end.
We’ll name these left and right , but they could be anything you’d like:
function isPalindrome(string) let left = 0; let right = string.length - 1; >
In an example string, these two pointers would start in the following locations:
Now, let’s write the loop that we’ll do all of our logic inside of. We’ll use a while loop here, since we want the loop to continue perpetually until its end-case is met, when we reach the «middle» of the string:
function isPalindrome(string) let left = 0; let right = string.length - 1; while (left right) > >
This works because we know that if left ever becomes greater than right , that means we’ve passed the middle of the string and we shouldn’t be continuing our loop.
Now we’ll implement our core bit of logic, and the incrementing/decrementing of our pointers to traverse the string:
function isPalindrome(string) let left = 0; let right = string.length - 1; while (left right) if (string[left] !== string[right]) return false; left++; right--; > >
What we’re doing here is using a comparison operator to check if the character on the left does not match the character on the right. If this is the case, we know that the string can’t be a palindrome, and we immediately return false as our function’s output.
If the characters do match, we know we should continue to traverse the string, and we increment the left pointer and decrement the right pointer respectively.
Now, all that’s left to do is put in our other return value, if the string is a palindrome:
function isPalindrome(string) let left = 0; let right = string.length - 1; while (left right) if (string[left] !== string[right]) return false; left++; right--; > return true; >
The true return value is outside of the while loop, because if we complete the loop without ever returning a false value, that means we’ve confirmed the string to be a palindrome.
If you’ve read this far, I hope this little tutorial helped in understanding this fundamental bit of algorithmic logic.
While this solution may be very simple, it’s important to keep in mind for more complex problems and algorithms where you may need to expand on it, or use it nested further within a greater problem. I can guarantee you that it will show up in your studies or assessments at some point, in some form!
Thanks so much for reading, and happy coding. 😄
Top comments (11)
Thanks for sharing, i don’t understand why you made it so complicated?
Just convert the string into an array with split, reverse the returned array, convert it into a string with join and compare it with the original string.
const isPalindrome = str => str.split('').reverse().join('') === str;
12 likes Like Comment button
I think the author’s main goal is to show the reader how to check if a string is a palindrome algorithmically, using javascript methods is fine but it makes the code idiomatic/would make most sense for a js dev.
Also, generally performance should never be a primary factor. Writing clean, easy to understand and maintainable code is the goal any dev should have. Because your example is idiomatic to js devs in a js codebase it will seem more intuitive to any new dev as opposed to the author’s.
I saw a few comments talking about perf. Performance shouldn’t be a decision factor. Performance can be optimized if it becomes a problem.
9 likes Like Comment button
Full-Stack Software Engineer; using a background in Acting and Voice-Over to pursue a lifelong love of software and technology from an arts and humanities perspective.
Yes, this was originally my goal. I love this that sparked so much discussion on different ways of approaching the same problem!
I mainly approached this (relatively simple problem) from the perspective of how someone might solve it in a more language agnostic, algorithmic way that touched on a few other aspects of problem solving that new developers might not have as much practice with, like moving pointers and checking/comparing string characters similar to how you might compare array elements.
I was aiming for more of an informational approach than the simplest solution, but I appreciate that there are comments on here now for folks to see other solutions that work as well (especially using in-built JS methods, since that’s a perfectly valid approach too.) 😃
6 likes Like Comment button
generally performance should never be a primary factor
The combination of generally and never seems confused. and the sentiment is troubling.
Especially when developing software libraries,
- you aren’t positioned to understand whether performance compromises are problematic, and
- the client isn’t in positioned to resolve those problems
Empathy should be out guiding principle, both for those inheriting and maintaining the code we write and for those consuming it.
«generally» => most cases so you can read it out as «in most cases, performance should never», which means performance should only be a deciding factor in specific situations where the operation is costly in some way, is used frequently, etc.
For example, the palindrome code from the post doesn’t have to be optimized for performance but say you were batching a bunch of expensive asynchronous tasks, you could use Promise.all and generators together to do so. The question you should ask before working on this optimization is whether or not maintaining that extra complexity is going to bring any net benefit. For the palindrome example, there’s little to no net benefit so going with an idiomatic approach is fine, even if it’s slower.
I don’t understand why you think that a library author is in no position to determine whether or not a performance compromise is problematic. Making decisions like that is literally the job of a developer. True, consumer’s are in no position to resolve such problems, and that’s exactly why building healthy communities is important, so consumers come back to you and tell you that something isn’t doing the job well (when it comes to libraries, for product consumers, you can use analytics, performance metrics, etc.)
Yes, Empathy should be every developer’s guiding principle, and unnecessary performance optimizations have nothing to do with being empathetic. I’m not saying optimizations are unnecessary but optimizing unnecessarily, is unnecessary.
1 like Like Comment button
JavaScript Program to Check Whether a String is Palindrome or Not
To understand this example, you should have the knowledge of the following JavaScript programming topics:
A string is a palindrome if it is read the same from forward or backward. For example, dad reads the same either from forward or backward. So the word dad is a palindrome. Similarly, madam is also a palindrome.
Example 1: Check Palindrome Using for Loop
// program to check if the string is palindrome or not function checkPalindrome(string) < // find the length of a string const len = string.length; // loop through half of the string for (let i = 0; i < len / 2; i++) < // check if first and last string are same if (string[i] !== string[len - 1 - i]) < return 'It is not a palindrome'; >> return 'It is a palindrome'; > // take input const string = prompt('Enter a string: '); // call the function const value = checkPalindrome(string); console.log(value);
Enter a string: madam It is a palindrome
In the above program, the checkPalindrome() function takes input from the user.
- The length of the string is calculated using the length property.
- The for loop is used to iterate up to the half of the string. The if condition is used to check if the first and the corresponding last characters are the same. This loop continues till the half of the string.
- During the iteration, if any character of the string, when compared with its corresponding last string is not equal, the string is not considered a palindrome.
Example 2: Check Palindrome using built-in Functions
// program to check if the string is palindrome or not function checkPalindrome(string) < // convert string to an array const arrayValues = string.split(''); // reverse the array values const reverseArrayValues = arrayValues.reverse(); // convert array to string const reverseString = reverseArrayValues.join(''); if(string == reverseString) < console.log('It is a palindrome'); >else < console.log('It is not a palindrome'); >> //take input const string = prompt('Enter a string: '); checkPalindrome(string);
Enter a string: hello It is not a palindrome
In the above program, the palindrome is checked using the built-in methods available in JavaScript.
- The split(») method converts the string into individual array characters.
const arrayValues = string.split(''); // ["h", "e", "l", "l", "o"]
// ["o", "l", "l", "e", "h"] const reverseArrayValues = arrayValues.reverse();
const reverseString = reverseArrayValues.join(''); // "olleh"
Note: The multiple lines of code can be reduced and written in one line:
const reverseString = string.split('').reverse().join('');