Palindrome Number - Leetcode 9 - Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 11 ก.ย. 2024

ความคิดเห็น • 120

  • @vigilante191
    @vigilante191 4 หลายเดือนก่อน +54

    thanks for making me more confused

    • @ananttyagi4577
      @ananttyagi4577 2 หลายเดือนก่อน +4

      it's pretty simple sir, please do put some efforts

    • @manavjain9750
      @manavjain9750 2 หลายเดือนก่อน

      Are you ASIAN?

  • @aspar13
    @aspar13 ปีที่แล้ว +13

    Nice Solution!
    We can write the divider value in this way as well 8:37:
    if x==0: return True
    div = 10**int(math.log10(x))

    • @maaz2004
      @maaz2004 3 หลายเดือนก่อน

      bro ain't nobody trynna use the log function

    • @nikhilaradhya4088
      @nikhilaradhya4088 2 หลายเดือนก่อน

      You have to take the floor of the log

  • @anandsharma16
    @anandsharma16 3 หลายเดือนก่อน +6

    watched this and did it using strings, gave myself a pat on the back.

    • @esaur5310
      @esaur5310 2 หลายเดือนก่อน +1

      a lot easier and you are using a data structure;
      #O(n)
      tmp_str = str(x)
      if tmp_str[::-1] == str(x):
      return True
      else:
      return False
      was my solution O(n) time too

    • @manavjain9750
      @manavjain9750 2 หลายเดือนก่อน

      ​@@esaur5310sir I didn't really understand could you explaim

  • @nisimkd1
    @nisimkd1 6 หลายเดือนก่อน +1

    Great solution, thank you!
    The solution implemented in c#:
    public bool IsPalindrome(int x) {
    if (x < 0)
    {
    return false;
    }
    long divider = 1;
    while (divider * 10 0)
    {
    int l = (int) (x / divider);
    int r = (int) (x % 10);
    if (l != r)
    {
    return false;
    }
    // Cut the left digit
    x = (int) (x % divider);
    // Cut the right digit
    x /= 10;
    divider /= 100;
    }
    return true;
    }
    divider is in long type due to case the given x is one digit less the max int value.
    Another solution, write the reserved number and compare it to the given x.
    implemented in c#:
    public bool IsPalindrome(int x) {
    if (x < 0)
    {
    return false;
    }

    int reservedNumber = 0;
    int originalX = x;
    while (x > 0)
    {
    int lastDigit = x % 10;
    reservedNumber = reservedNumber * 10 + lastDigit;
    x /= 10;
    }
    return reservedNumber == originalX;
    }

  • @kaankahveci1153
    @kaankahveci1153 10 หลายเดือนก่อน +9

    I feel like this is a simpler approach:
    public class Solution {
    public bool IsPalindrome(int x) {
    if(x < 0) return false;
    if (x != 0 && x % 10 == 0) return false;
    int original = x;
    int reversed = 0;
    while (x != 0) {
    reversed = reversed * 10 + x % 10;
    x /= 10;
    }
    return original == reversed;
    }
    }

  •  3 ปีที่แล้ว +8

    This was my C# solution (which is similar to yours) that I submitted a while ago;
    if(x == 0)
    return true;
    if(x < 0 || x % 10 == 0)
    return false;

    var reverse = 0;

    while(x > reverse)
    {
    var lastDigit = x % 10;
    x /= 10;
    reverse = reverse * 10 + lastDigit;
    }

    return x == reverse || x == reverse / 10;

  • @marioalfredojorge1204
    @marioalfredojorge1204 3 หลายเดือนก่อน +1

    A simple solution using JS. The idea is to reverse the number and then compare it to the original one.
    var isPalindrome = function(x) {
    if (x < 0) return false;
    let num = x;
    let result = 0;
    while (num > 0) {
    result = result * 10 + (num % 10);
    num = Math.floor(num / 10);
    }
    return result === x;
    };

  • @babacarkane1027
    @babacarkane1027 ปีที่แล้ว +2

    Simple, efficient and straight to the point. Thanks for this answer.

  • @KumarMukand-dm9iw
    @KumarMukand-dm9iw 2 หลายเดือนก่อน +1

    Easiest Way Ever :
    def isPalindrome(self, x):
    num = x
    reverse = 0
    while(x>0):
    lastdigit = x%10
    reverse = reverse*10+lastdigit
    x = x//10
    return True if reverse == num else False

    • @nupoornawathey100
      @nupoornawathey100 2 หลายเดือนก่อน +1

      Yes it's right, I think there's a type in your solution
      This line should be x = x//10 instead of x = x/10

    • @PrakashCreates149
      @PrakashCreates149 22 วันที่ผ่านมา

      this is evergreen solution

  • @iforcollege
    @iforcollege 2 ปีที่แล้ว +4

    I think this video may need a remake because it will not work when the input is 1410110141 on Java. I tried this and it worked:
    if (x < 0 || (x % 10 == 0 && x != 0)) {
    return false;
    } else {
    int original = x, reversed = 0;
    while (original > reversed) {
    reversed = (reversed * 10) + (original % 10);
    original /= 10;
    }
    return original == reversed || original == reversed / 10;
    }

    • @zawarudo6389
      @zawarudo6389 2 ปีที่แล้ว

      i used long long type for div and it worked

    • @iforcollege
      @iforcollege 2 ปีที่แล้ว

      @@zawarudo6389 There is only long in Java I think. Your method works but it still runs a bit slower. Thanks for the reply though.

    • @zawarudo6389
      @zawarudo6389 2 ปีที่แล้ว

      @@iforcollege i implemented in c++ and it was not slow even when using long long it beats 98% of cpp submissions

  • @bennychristiyan2646
    @bennychristiyan2646 2 หลายเดือนก่อน +2

    s = str(x)
    return s == s[::-1]
    This code is more effective and very simple to understand. Hope it was useful

    • @ssrishtix4142
      @ssrishtix4142 หลายเดือนก่อน +3

      but the follow up says we can't convert it to string

    • @bennychristiyan2646
      @bennychristiyan2646 3 วันที่ผ่านมา

      It worked for me. I don't think such condition is given in the question

  • @sepia2008
    @sepia2008 6 วันที่ผ่านมา

    What if you try to recreate the number by chopping its rightmost value and add it back:
    for example 121 i break it by doing % 10 to get the 1 from the right side, then do *10 and adding 20 and so on and in the end you check if x is equal to your new formed value (y let's say) if true that's what you return as well.

    • @sepia2008
      @sepia2008 6 วันที่ผ่านมา

      Do you think this might be slower than the 2 pointer option you mention here ?

  • @prabinlamsal74
    @prabinlamsal74 ปีที่แล้ว +4

    Will this solution work for this testcase?
    1000021
    Because, once we remove the first and the last letter and proceed to the next step,
    we have
    000021 which is evaluated as 21

    • @somanshv4992
      @somanshv4992 ปีที่แล้ว +1

      Doesnt work for this case!

    • @divetilps
      @divetilps ปีที่แล้ว

      @@somanshv4992 works just fine

    • @paperplane-db8qf
      @paperplane-db8qf 11 หลายเดือนก่อน

      you need to alter the code to not change the input and just get the digits using two pointers.

  • @Xuze
    @Xuze 2 ปีที่แล้ว +15

    This solution will fail if the number contains "0" in the middle of a number right? Like 1000021

    • @patrickoweijane559
      @patrickoweijane559 2 ปีที่แล้ว +3

      It should not fail, I just tested it. I had this problem because my condition in the while loop was different.

    • @odinson4184
      @odinson4184 2 ปีที่แล้ว +1

      @@patrickoweijane559 How? Removing the first integer from 100021 with modulos for example produces 21 instead of 00021. It doesn't work.

    • @ventior6806
      @ventior6806 2 ปีที่แล้ว +1

      @@odinson4184 Because that is how it is supposed to work. You loop over and over again. 120021 for example goes to 2002 - 00. You always strip the outer two numbers and check with if left != right if they matchup. At the point where they don't you return false.
      In your case with 100021 you strip the left and right number: 0002. Then in the next loop you get the left with 0002//1000 = 0 and the right with 0002%10 = 2. Which in turn returns False with left != right.
      EDIT: I think I've noticed the error in your thinking. You mentioned that 00021 returns 21 correct? That is not how Modulos works. It first divides 20 by 10 which is 2 and dismisses it. Then it takes the 1 and divides it again by 10, which, of course, doesn't work and returns 1. The Modulo Operator always returns the digit it can't divide.

    • @odinson4184
      @odinson4184 2 ปีที่แล้ว

      @@ventior6806 NO- stripping 1 from 100021 returns 21. This method just doesn't work. I copied it word for word, you have to use other method to solve.

    • @ventior6806
      @ventior6806 2 ปีที่แล้ว

      @@odinson4184 Well it works for me, I don't know what your problem is. To strip the left 1 you divide by "div". For the right 1 you use x%10. I honestly don't know why it doesn't work for you.

  • @zerkinanastya4410
    @zerkinanastya4410 ปีที่แล้ว +2

    Thank you for the solution! But I’m struggling to understand why we should chop off the left and right digits, couldn’t we just compare then and if they are equal return True? Please if someone could explain, I would be much grateful!

    • @germainsafari8671
      @germainsafari8671 ปีที่แล้ว

      the last condition returns False clarify that if the middle numbers are equal then True. we need to remove right and left numbers so that we can compare the middle numbers.

  • @metawrld_dream
    @metawrld_dream หลายเดือนก่อน

    Do you know how to fix this code to work with 0’s on both ends, say you end up with 0110, I think the computer will ignore the first 0 so it’ll try to match 1 and 0 which will return false, idk if this happens on python but i’m doing it in java

  • @pavel.pavlov
    @pavel.pavlov 10 หลายเดือนก่อน

    you could use decimal log for finding the divider

  • @iamburntout
    @iamburntout 7 หลายเดือนก่อน +1

    why don't we just reverse the number and compare?

  • @rehatsingh5208
    @rehatsingh5208 3 หลายเดือนก่อน +1

    Damm. I created a linked list and rebuilt the number in reverse and then compared it. And that too in C. 😭😭

  • @TheElementFive
    @TheElementFive 2 ปีที่แล้ว +5

    A rather contrived problem. Not a fan. Great explanation though!

  • @ChangKaiHua300
    @ChangKaiHua300 2 ปีที่แล้ว +1

    class Solution:
    def isPalindrome(self, x: int) -> bool:
    list1=[]
    import math
    y = [a for a in str(x)]
    for i in range(0,math.floor(len(y)/2)+1):
    if y[i]!=y[-i-1]:
    list1.append(1)
    else:
    list1.append(0)
    if 1 in list1:
    return False
    return True

    • @RockyScenes
      @RockyScenes 2 ปีที่แล้ว

      can you explain this

  • @sangpark7656
    @sangpark7656 ปีที่แล้ว +1

    why do you assume 21/10 rounds down to 2?

    • @ridazouga4144
      @ridazouga4144 5 หลายเดือนก่อน +1

      In python for example 21//10 (note the double division sign) it returns integer division which will be 2, and to understand it think of it as first we do simple division which result will be 2.1 but then discard decimal value, so for example 3//4 will return 0 since we discarded decimal value

  • @LethaL0702
    @LethaL0702 2 หลายเดือนก่อน

    Correct me if I am wrong but this solution is outdated. It fails for the test case 1000021.

  • @gumogumo7996
    @gumogumo7996 2 ปีที่แล้ว +3

    class Solution:
    def isPalindrome(self, x: int) -> bool:
    return str(x) == str(x)[::-1]

  • @manavjain9750
    @manavjain9750 2 หลายเดือนก่อน

    Great explanation sir ... respect!

  • @zmm978
    @zmm978 11 หลายเดือนก่อน

    this one needs update, doesn't work on x0000xx

  • @Squash101
    @Squash101 8 หลายเดือนก่อน

    wait there are pointers in python?

  • @omaryapping
    @omaryapping หลายเดือนก่อน +1

    Sure it's a smart solution but who tf is coming up with this in an interview (unless you've memorised it)

  • @BineeshDharmajan
    @BineeshDharmajan หลายเดือนก่อน

    congrats for 350K😍

  • @rahulmahadik5787
    @rahulmahadik5787 6 หลายเดือนก่อน +1

    can anyone tell me why you gotta use oops in this when it simply can be done using if else statement correct me if i am wrong heres my code btw
    x=121
    y=str(x)[-1::-1]
    z=int(y)
    print(z)
    if x == z:
    print("Palindrome")
    else:
    print("not a palindrome")
    it didnt ran on leetcode showed some sort of runtime error

    • @vigilante191
      @vigilante191 4 หลายเดือนก่อน

      make a simple problem very complex ...solve it..and boom people will call you INTELLECTUAL

    • @جمعانبنسويد
      @جمعانبنسويد 4 หลายเดือนก่อน +1

      @decimusmeridious4444
      Because the follow up question in the problem said
      CAN you solve it WITHOUT convert the int to string?
      That's why it's not allowed that solution...(It will accept it but that not how they want you to solve it) the problem is about int manipulation....

  • @joshfeldman7586
    @joshfeldman7586 ปีที่แล้ว

    heres mine
    class Solution:
    def isPalindrome(self, x: int) -> bool:
    z = str(x)[::-1]
    if z == str(x):
    return True
    else :
    return False

  • @ArchawatThongroi
    @ArchawatThongroi 3 หลายเดือนก่อน

    thanks you for your solution brother !!

  • @SelimAbidin
    @SelimAbidin 2 ปีที่แล้ว +1

    It is interesting how the solution is here. Does it really work in python when the number is something like 10000001?
    My solution was something like this. It is enough fast but I wanted to have memory optimized. :(
    var isPalindrome = function(x) {

    if (x < 0) return false
    if (x < 10) return true
    var array = []
    while (x != 0) {
    array.push(x % 10)
    x = parseInt(x / 10)
    }

    for (var i = 0; i< parseInt(array.length / 2); i++) {
    var start = array[i]
    var end = array[array.length - (i + 1)]
    if (start != end) return false
    }

    return true
    };

    • @hypnoz123
      @hypnoz123 ปีที่แล้ว

      X < 10 return false will fail. One of the tests is on 0, which it expects to return true

    • @somanshv4992
      @somanshv4992 ปีที่แล้ว +2

      Your solution works just fine. The 10000021 case failed, but your code handles it. But with a lot of time and space overhead.

  • @lasredchris
    @lasredchris 3 ปีที่แล้ว

    at 11:56 Why do we do div = div / 100 and not div = div/10 ?

    • @mohammadal-abbasi6155
      @mohammadal-abbasi6155 3 ปีที่แล้ว +2

      @Chris Sun because the line right above it is modifying x by a factor of 100 (by chopping off two digits). If you reduce x from 1221 to 22, you want your div to go from 1000 (used for 1221), to 10 (to be used for 22).

  • @yogeshchandrasekharuni2727
    @yogeshchandrasekharuni2727 ปีที่แล้ว +1

    This does not work for a number like 100021

    • @bereketyisehak5584
      @bereketyisehak5584 ปีที่แล้ว

      It works fine for me. The if statement return false when it does (0002//1000 != 0002%10).

  • @jiquandeng7110
    @jiquandeng7110 ปีที่แล้ว

    class Solution(object):
    def isPalindrome(self, x):
    b=str(x)
    c=b[::-1]
    if c==b:
    return True
    else:
    return False

    • @randytruong6621
      @randytruong6621 ปีที่แล้ว

      time complex is very slow because converting to a string and slicing a string

  • @rmwk991
    @rmwk991 11 หลายเดือนก่อน

    Thank you!

  • @Andre-rk1py
    @Andre-rk1py 2 ปีที่แล้ว +3

    damn, I just converted the number to a string, used [::-1] to turn it around, converted it to a number again with int, and compared it with the original x, I think something is wrong with me

    • @Levelord92
      @Levelord92 2 ปีที่แล้ว

      there is nothing wrong with you. It's a natural solution. But every problem in leetcode is tougher than it seems

    • @hickasso
      @hickasso 2 ปีที่แล้ว

      I thought the same way

  • @prativa810
    @prativa810 ปีที่แล้ว

    Nice explanation! What would be the time complexity of the solution? O(logN) ??

    • @rishenglian9959
      @rishenglian9959 ปีที่แล้ว +4

      The answer should be O(N), the worst case is when the program checks a positive palindrome number, every time the number is chopped off by 2 digits, then the whole process will contain N/2 iteration steps.

    • @davisonyeoguzoro9232
      @davisonyeoguzoro9232 ปีที่แล้ว

      @@rishenglian9959 Please more explanation no this

    • @impro9118
      @impro9118 ปีที่แล้ว +2

      @@davisonyeoguzoro9232 Late response but esentially every step of the loop you reduce the size of the number by 2, so if you have a 20 numbers integer it will take 10 steps to reduce it completely. This scales linearily and thus is O(n/2) which is O(n)

  • @user-xk2zy3ng1o
    @user-xk2zy3ng1o ปีที่แล้ว

    O(log10N) , right?

  • @Rohitkumar-xv7uv
    @Rohitkumar-xv7uv 2 ปีที่แล้ว +5

    def isPalindrome(self, x: int) -> bool:
    x = str(x)
    if x[::-1] == x:
    return True
    else:
    return False

  • @chinmaikhare2198
    @chinmaikhare2198 ปีที่แล้ว

    we can simply change it to string?

  • @germainsafari8671
    @germainsafari8671 ปีที่แล้ว

    Anyone knows why do we need to divide div by 100? The condition div = div // 100.

    • @jessakwest
      @jessakwest ปีที่แล้ว

      be were removing both the first + last digits, we change the divider by 100

  • @carloslazarin
    @carloslazarin ปีที่แล้ว

    impresive

  • @monkmonah1
    @monkmonah1 ปีที่แล้ว +1

    How about making inverted number (java) public boolean isPalindrome(int x) {
    if (x < 0) {
    return false;
    }
    int inverted = 0;
    for (int target = x; target != 0; target /= 10) {
    inverted = inverted * 10 + target % 10;
    }
    return inverted == x;
    }

    • @black_wind2794
      @black_wind2794 11 หลายเดือนก่อน

      this version passes all the test cases on leetcode contrary to the solution proposed in the video

  • @sherrypan6029
    @sherrypan6029 2 ปีที่แล้ว +3

    return str(x) == str(x) [::-1]

  • @ritiksingh2692
    @ritiksingh2692 ปีที่แล้ว

    can you give the same solution in java pls

  • @pawankishorsingh
    @pawankishorsingh 3 ปีที่แล้ว

    The "Problem Link" is wrong in your description. Please correct it.

    • @NeetCode
      @NeetCode  3 ปีที่แล้ว

      sorry about that, fixed!

  • @k.alipardhan6957
    @k.alipardhan6957 2 ปีที่แล้ว +9

    return str(x) == str(x)[::-1]
    Runtime: 115 ms, faster than 21.82% of Python3 online submissions for Palindrome Number.
    Memory Usage: 13.9 MB, less than 90.68% of Python3 online submissions for Palindrome Number.

    • @jesseemamalie9728
      @jesseemamalie9728 ปีที่แล้ว +3

      Nice! But it doesn't cover the follow up question "Could you solve it without converting the integer to a string?". This video shows the follow up question's solution.

  • @sreedeepthichigurupati2824
    @sreedeepthichigurupati2824 ปีที่แล้ว +1

    I did this in Java. Runtime and memory same to be the same as above solution.
    public boolean isPalindrome(int x) {
    if(x == 0)
    return true;
    if(x < 0 || x % 10 == 0)
    return false;
    List arr = new ArrayList();
    while(x > 0){
    int temp = x%10;
    x=x/10;
    arr.add(temp);
    }
    int start = 0, end = arr.size() - 1;
    while(start

    • @cengprog9529
      @cengprog9529 8 หลายเดือนก่อน

      Ngl, but this is quite easy to understand. The code is short & precise, plus it works well. Thanks for sharing out the code

  • @Hetshah25
    @Hetshah25 ปีที่แล้ว +2

    What if we just compare string with reversed string. Isn't that an easy solution?
    def isPalindrome(self, x: int) -> bool:
    if(x

    • @mrtech7940
      @mrtech7940 ปีที่แล้ว +1

      thanks man that was way more easier

    • @c1inward346
      @c1inward346 ปีที่แล้ว +7

      there is a follow up question: can you solve the problem without converting it into string?

  • @jakobleo3440
    @jakobleo3440 3 ปีที่แล้ว

    wonderful video!

  • @piyushthakur734
    @piyushthakur734 5 หลายเดือนก่อน

    Is this solution good?
    number = int(input())
    list = []
    new_list = list.append(number)
    print(list)
    string = str(number)
    new_string=string[::-1]
    new_string1 = int(new_string)
    list2 = [new_string1]
    if list[0]==list2[0]:
    print("It is pallindrome")
    else:
    print("It is not pallindrome")

    • @LethaL0702
      @LethaL0702 2 หลายเดือนก่อน

      Nope, you are converting the number to a string. Not sure why are you using a list.

  • @mackenziestewart1500
    @mackenziestewart1500 ปีที่แล้ว

    Check this out, much easier to visualize
    class Solution:
    def isPalindrome(self, x: int) -> bool:
    if x

    • @whetfaartz6685
      @whetfaartz6685 7 หลายเดือนก่อน

      That answer is too easy, the interview question is going to want you to solve it without converting to a string

  • @rajendarsingh9333
    @rajendarsingh9333 3 ปีที่แล้ว

    please solve top view and bottom view of binary tree

  • @manikhanthkatti3448
    @manikhanthkatti3448 3 ปีที่แล้ว +1

    First again ❤️

  • @animelegaxy
    @animelegaxy 3 ปีที่แล้ว

    Does anyone came up with the c++ soln with this approach

    • @freeguy240
      @freeguy240 2 ปีที่แล้ว

      bool isPalindrome(int x) {
      if(x=10*div)
      div*=10;

      while(x)
      {
      int right=x%10;
      int left=x/div;

      if(left!=right)
      return false;

      x=(x%div)/10;
      div=div/100;
      }

      return true;
      }

  • @APudgyPanda96
    @APudgyPanda96 2 ปีที่แล้ว +2

    What a stupid problem

  • @peter-eh2oq
    @peter-eh2oq 2 ปีที่แล้ว +2

    this is wrong

  • @DevMaster-13
    @DevMaster-13 ปีที่แล้ว

    Will this work?
    x_str = str(x)
    return x_str == x_str[::-1]

    • @licokr
      @licokr 6 หลายเดือนก่อน

      the point is not to covert from integer to string

  • @akhmadillom
    @akhmadillom ปีที่แล้ว

    Thank you!

  • @venkatbalachandra5965
    @venkatbalachandra5965 ปีที่แล้ว

    class Solution:
    def isPalindrome(self, x: int) -> bool:
    return (str(x)==str(x)[::-1])