DEV Community

Cover image for How to Solve Palindrome Problem with 1 Line of JavaScript
Amit Mehta
Amit Mehta

Posted on • Originally published at indepthjavascript.dev

How to Solve Palindrome Problem with 1 Line of JavaScript

Unless you're just learning how to code now, you've probably heard of the famous valid palindrome or 'is palindrome' problem. It's a common technical interview question.

I'm going to show you how to knock the socks off your interviewer by solving the palindrome problem in 1 line of JavaScript. 😎

javascript-1-line-surprised.png

Quick Refresher: What is the Palindrome Problem?

A string is a palindrome, if after reversing the order of all the characters, you get the same string. const str = 'abba' is a palindrome, const str = 'abc' is not.

Here's the challenge: Given a valid string of letters, can you construct a function that will check if the string is a valid palindrome. It returns true if it is, and false if it's not.

IsPalindrome(...) in 1 Line

const isPalindrome = (str, first = 0, last = str.length - 1) => 
  (first > last) ? 
    true : 
    (str[first] === str[last]) && isPalindrome(str, first + 1, last - 1);

Enter fullscreen mode Exit fullscreen mode

Yes, this is 1 line of JavaScript code. I added a few line breaks and tabs to make it easier to read.

If the above function looks overwhelming to you, no worries, we're going to walkthrough all the JavaScript and Recursion Jui Jitsu together. πŸ˜…

Let's start with...

Arrow Function

I'm using a JavaScript arrow function so I can remove return and taken advantage of implicit return feature the arrow function offers. Love arrow functions! 😍

const isPalindrome = (str, first = 0, last = str.length - 1) => 
Enter fullscreen mode Exit fullscreen mode

Default values for function arguments

We've initialized our 2 pointers right in the function argument: first = 0 and last = str.length - 1. Super cool and convenient.

Ternary operator

  (first > last) ? 
    true : 
    (str[first] === str[last]) && isPalindrome(str, first + 1, last - 1);
Enter fullscreen mode Exit fullscreen mode

The ternary conditional operator is just a if {...} else {...} statement condensed onto 1 line. Here's a simple example:

(x > 0) ? 
console.log('x is greater than zero') : 
console.log('x is less than or equal to zero');
Enter fullscreen mode Exit fullscreen mode

Finally Everyone's Favorite: Recursion!

(str[first] === str[last]) && isPalindrome(str, first + 1, last - 1);
Enter fullscreen mode Exit fullscreen mode

Fortunately, this is a simple application of recursion that won't give anyone a headache trying to comprehend it. 🀯

In the above statement: (str[first] === str[last]) checks to make sure the first and last characters of the string are matching. * Then isPalindrome(str, first + 1, last - 1) recursively checks if the 2nd and 2nd to last characters of the string are matching.*

For example: If we ran str = abcba through isPalindrome(str), and expanded out the final return statement (after running through each iteration of recursion) it would look like this:

(str[0] === str[4]) && (str[1] === str[3]) && (str[2] === str[2]) && true
Enter fullscreen mode Exit fullscreen mode

isPalindrome(str) is checking each pair of elements starting with str[0] versus str[4] (a vs a), until finally it's checking str[2] against itself when first === last.

The true statement at the end is tacked on when first > last, completing the last recursive function call.

Wait! What if I have to deal with spaces, uppercase, and weird characters??

OK, yea, in some Palindrome problems, such as this leetcode version you have strings with space, special characters and different cases that you have to remove or somehow deal with.

Fear not, there's a 1 line fix to cleaning up the string so it contains only lowercase letters. Run this before running isPalindrome(str):

str = str.match(/[a-z]/gi).join('').toLowerCase();
Enter fullscreen mode Exit fullscreen mode

or we can keep isPalindrome to 1 line, like I promised:

const isPalindrome = (str = str.match(/[a-z]/gi).join('').toLowerCase(), first = 0, last = str.length - 1) => 
  (first > last) ? 
    true : 
    (str[first] === str[last]) && isPalindrome(str, first + 1, last - 1);

Enter fullscreen mode Exit fullscreen mode

cat palindrome

Top comments (6)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Why so long and complex?

const isPalindrome = a => [...a].reverse().join('') === a
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lnquy065 profile image
Quy Luong

it's properly right, but I think in coding interview we can't do like that 😁

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

If I were interviewing a candidate and they gave me that solution, I'd be perfectly happy - it shows knowledge of modern JS and is an efficient solution.

Collapse
 
apmfree78 profile image
Amit Mehta

nice! interviewer may bawk at using reverse(), but hey if you can do it in 1 line, why not! 🀣

Collapse
 
simcha profile image
Simcha

:(
I read the post, and I don't understand why the author rowed...
And you confirmed my suspicions.

Collapse
 
coditdoc profile image
Codeitdoc7 • Edited

What if throw in some random characters. Like - ra@c#ec_aR