DEV Community

Cover image for How to Determine if a String is a Palindrome (in JavaScript)

How to Determine if a String is a Palindrome (in JavaScript)

Sean Welsh Brown on October 28, 2020

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 whe...
Collapse
 
mberger75 profile image
Marc Berger • Edited

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;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
wannabehexagon profile image
ItsThatHexagonGuy • Edited

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.

Collapse
 
seanwelshbrown profile image
Sean Welsh Brown • Edited

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.) 😃

Collapse
 
apmccartney profile image
Austin McCartney

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,

  1. you aren't positioned to understand whether performance compromises are problematic, and
  2. 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.

Thread Thread
 
wannabehexagon profile image
ItsThatHexagonGuy • Edited

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

Collapse
 
trongtai37 profile image
trongtai37

Hi, i think your code look shorter and cleaner but the fact that author's code run faster with less complexity!.

Collapse
 
gustavosfq profile image
Gustavo Flores
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;    
}

const isPalindrome2 = str => str.split('').reverse().join('') === str;

console.time('isPalindrome');
for(var i = 0; i < 100000000; i++) {
    isPalindrome('asdfgfdsa')
}
console.timeEnd('isPalindrome')
console.time('isPalindrome2');
for(var i = 0; i < 100000000; i++) {
    isPalindrome2('asdfgfdsa')
}
console.timeEnd('isPalindrome2')    
isPalindrome: 4212.408935546875 ms
isPalindrome2: 60999.298095703125 ms
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
amplanetwork profile image
Ampla Network • Edited

Not so sure either we can do shorter and faster :-)

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;    
}

const isPalindrome2 =(str) => {
  const l = str.length;
  for(let i=0; i< (l / 2) >> 0; i++) {
    if (str[i] !== str[l-i-1]) return false;
  }
  return true;
}

console.time('isPalindrome');
for(var i = 0; i < 100000000; i++) {
    isPalindrome('asdfgfdsa')
}
console.timeEnd('isPalindrome')
console.time('isPalindrome2');
for(var i = 0; i < 100000000; i++) {
    isPalindrome2('asdfgfdsa')
}
console.timeEnd('isPalindrome2')    ;

VM254:26 isPalindrome: 3210.27978515625 ms
VM254:31 isPalindrome2: 2888.925048828125 ms
Enter fullscreen mode Exit fullscreen mode
Collapse
 
cyberhck profile image
Nishchal Gautam

Less complexity? About performance, you can scale out, you need to write code which is easy to maintain, read and modify, when you look at original method, you won't know what's going on without some serious effort, with second one, within 2-5 seconds you understand exactly what it's doing

Collapse
 
bretgeek profile image
bretgeek • Edited

Don't get me wrong I like your algorithmic way better (it's probably faster too) but I have been on a kick lately trying to make things smaller. In case this is useful for anyone here is what I came up with in 6 lines. (probably better ways to do it too... bit shifting?)

function isPalindrome(str){
let strArr = str.split('');
let rev = strArr.reverse();
let str2 = rev.join('');
return str === str2;
}
Enter fullscreen mode Exit fullscreen mode

Use like:

let p = isPalindrome('racecar');
console.log(p);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️
const isPalindrome = s=>[...s].reverse().join('')==s
Enter fullscreen mode Exit fullscreen mode