skip to Main Content

Given an integer x, return true if x is a
palindrome
, and false otherwise.

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Ans :

var isPalindrome = function(number) {
     if(number.toString() === number.toString().split("").reverse().join("")){
        return true
    }
 return false;
};

How to optimize more and reduse time complexity

3

Answers


  1. I am not sure which time complexity does the reverse function have (but I think it is O(n)).

    However, below it’s a function that does not use any string manipulation builtin but compares the digits starting from the indices in the middle of your number and then moves to the ones next to those, and so on, until it reaches the beginning/end of the number or it doesn’t find equal digits. It runs in O(n) (technically n/2 as worst case scenario when the number is palindrome).

    function isPalindrome(num) {
      if (num < 0) {
        return false
      } else {
        let len = num.toString().length
        let i, j
        if ((len%2) === 1) { //Odd number of digits
          i = len/2 - 1.5
          j = len/2 + 0.5
        } else {
          i = len/2 - 1
          j = len/2
        }
        while (num[i] === num[j]) {
          if (i == 0) {
            return true
          }
          i-=1
          j+=1
        }
        return false
      }
    }
    
    Login or Signup to reply.
  2. The palindrome algo is quite easy, just iterate characters from the beginning and the end of a string and compare, convert your number to a string first:

    function isNumPalindrome(num){
      const str = Math.abs(num).toString();
      for(let i=0, j=str.length-1; i<j; i++,j--){
        if(str[i] !== str[j]){
          return false;
        }
      }
      return true;
    }
    
    [123, 121, 121.121, 233332, 12332123, -123321].forEach(num => console.log(num, '=>', isNumPalindrome(num)));

    And benchmark:

    ` Chrome/118
    ------------------------------------------------------------
    small array
        Alexander   1.00x  |  x10000000  798  826  832  847  847
        Koolinc     1.47x  |   x1000000  117  117  120  122  132
    big array
        Alexander   1.00x  |  x10  210  215  215  219  225
        Koolinc     1.19x  |  x10  249  253  256  257  268
    ------------------------------------------------------------
    https://github.com/silentmantra/benchmark `
    
    const arr = [121, 2341, -122, 2332, 1221, 1, 127721, -1213121];
    
    const bigArr = Array.from({ length: 1_000_000 }, () =>
      Math.floor(1 + Math.random() * 1000000)
    );
    
    function reverseDigits(nr) {
      let reversed = 0;
      
      while (nr > 0) {
        reversed = reversed * 10 + nr % 10;
        nr = Math.floor(nr / 10);
      }
      
      return reversed;
    }
    
    
    function isPalindrome(nr) {
      nr = Math.abs(nr);
      return nr < 10 ? `n/a` : nr === reverseDigits(nr);
    }
    
    function isNumPalindrome(num){
      const str = Math.abs(num).toString();
      for(let i=0, j=str.length-1; i<j; i++,j--){
        if(str[i] !== str[j]){
          return false;
        }
      }
      return true;
    }
    
    // @group small array
    
    // @benchmark Koolinc
    arr.forEach(isPalindrome);
    true;
    
    // @benchmark Alexander
    arr.forEach(isNumPalindrome);
    true;
    
    // @group big array
    
    // @benchmark Koolinc
    bigArr.forEach(isPalindrome);
    true;
    
    // @benchmark Alexander
    bigArr.forEach(isNumPalindrome);
    true;
    
    
    /*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));
    Login or Signup to reply.
  3. To reverse a number without (relative slow) string manipulation you can use a function that uses arithmetic for it:

    [121, 2341, -122, 2332, 1221, 1, 127721, -1213121]
      .forEach( nr => console.log(`${nr} ${isPalindrome(nr)}`));
    
    function reverseDigits(nr) {
      let reversed = 0;
      
      while (nr > 0) {
        reversed = reversed * 10 + nr % 10;
        nr = Math.floor(nr / 10);
      }
      
      return reversed;
    }
    
    function isPalindrome(nr) {
      nr = Math.abs(nr);
      return nr < 10 ? `n/a` : nr === reverseDigits(nr);
    }
    .as-console-wrapper {
        max-height: 100% !important;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search