No video

Palindrome Number - Leetcode 9 - Python

  Рет қаралды 69,791

NeetCode

NeetCode

Күн бұрын

Пікірлер: 117
@vigilante191
@vigilante191 4 ай бұрын
thanks for making me more confused
@ananttyagi4577
@ananttyagi4577 2 ай бұрын
it's pretty simple sir, please do put some efforts
@manavjain9750
@manavjain9750 2 ай бұрын
Are you ASIAN?
@aspar13
@aspar13 Жыл бұрын
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 Ай бұрын
You have to take the floor of the log
@nisimkd1
@nisimkd1 5 ай бұрын
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; }
@anandsharma16
@anandsharma16 2 ай бұрын
watched this and did it using strings, gave myself a pat on the back.
@esaur5310
@esaur5310 2 ай бұрын
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
@babacarkane1027
@babacarkane1027 11 ай бұрын
Simple, efficient and straight to the point. Thanks for this answer.
@marioalfredojorge1204
@marioalfredojorge1204 3 ай бұрын
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; };
@kaankahveci1153
@kaankahveci1153 10 ай бұрын
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 жыл бұрын
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;
@bennychristiyan2646
@bennychristiyan2646 Ай бұрын
s = str(x) return s == s[::-1] This code is more effective and very simple to understand. Hope it was useful
@ssrishtix4142
@ssrishtix4142 Ай бұрын
but the follow up says we can't convert it to string
@iforcollege
@iforcollege 2 жыл бұрын
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 Жыл бұрын
i used long long type for div and it worked
@iforcollege
@iforcollege Жыл бұрын
@@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 Жыл бұрын
@@iforcollege i implemented in c++ and it was not slow even when using long long it beats 98% of cpp submissions
@manavjain9750
@manavjain9750 2 ай бұрын
Great explanation sir ... respect!
@zerkinanastya4410
@zerkinanastya4410 Жыл бұрын
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.
@KumarMukand-dm9iw
@KumarMukand-dm9iw Ай бұрын
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 Ай бұрын
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 8 күн бұрын
this is evergreen solution
@BineeshDharmajan
@BineeshDharmajan Ай бұрын
congrats for 350K😍
@pavel.pavlov
@pavel.pavlov 9 ай бұрын
you could use decimal log for finding the divider
@TheElementFive
@TheElementFive 2 жыл бұрын
A rather contrived problem. Not a fan. Great explanation though!
@ChangKaiHua300
@ChangKaiHua300 2 жыл бұрын
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
@prabinlamsal74
@prabinlamsal74 Жыл бұрын
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 Жыл бұрын
Doesnt work for this case!
@divetilps
@divetilps 11 ай бұрын
@@somanshv4992 works just fine
@paperplane-db8qf
@paperplane-db8qf 10 ай бұрын
you need to alter the code to not change the input and just get the digits using two pointers.
@rehatsingh5208
@rehatsingh5208 2 ай бұрын
Damm. I created a linked list and rebuilt the number in reverse and then compared it. And that too in C. 😭😭
@ArchawatThongroi
@ArchawatThongroi 2 ай бұрын
thanks you for your solution brother !!
@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
@gumogumo7996
@gumogumo7996 2 жыл бұрын
class Solution: def isPalindrome(self, x: int) -> bool: return str(x) == str(x)[::-1]
@iamburntout
@iamburntout 7 ай бұрын
why don't we just reverse the number and compare?
@Xuze
@Xuze 2 жыл бұрын
This solution will fail if the number contains "0" in the middle of a number right? Like 1000021
@patrickoweijane559
@patrickoweijane559 2 жыл бұрын
It should not fail, I just tested it. I had this problem because my condition in the while loop was different.
@odinson4184
@odinson4184 2 жыл бұрын
@@patrickoweijane559 How? Removing the first integer from 100021 with modulos for example produces 21 instead of 00021. It doesn't work.
@ventior6806
@ventior6806 2 жыл бұрын
@@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.
@sangpark7656
@sangpark7656 Жыл бұрын
why do you assume 21/10 rounds down to 2?
@ridazouga4144
@ridazouga4144 5 ай бұрын
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
@rmwk991
@rmwk991 10 ай бұрын
Thank you!
@LethaL0702
@LethaL0702 2 ай бұрын
Correct me if I am wrong but this solution is outdated. It fails for the test case 1000021.
@rahulmahadik5787
@rahulmahadik5787 6 ай бұрын
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
@user-pw2he2px3k
@user-pw2he2px3k 3 ай бұрын
@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....
@omaryapping
@omaryapping 18 күн бұрын
Sure it's a smart solution but who tf is coming up with this in an interview (unless you've memorised it)
@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
@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
@zmm978
@zmm978 10 ай бұрын
this one needs update, doesn't work on x0000xx
@Squash101
@Squash101 7 ай бұрын
wait there are pointers in python?
@k.alipardhan6957
@k.alipardhan6957 2 жыл бұрын
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 Жыл бұрын
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.
@SelimAbidin
@SelimAbidin Жыл бұрын
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 Жыл бұрын
Your solution works just fine. The 10000021 case failed, but your code handles it. But with a lot of time and space overhead.
@yogeshchandrasekharuni2727
@yogeshchandrasekharuni2727 Жыл бұрын
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).
@Rohitkumar-xv7uv
@Rohitkumar-xv7uv 2 жыл бұрын
def isPalindrome(self, x: int) -> bool: x = str(x) if x[::-1] == x: return True else: return False
@prativa810
@prativa810 Жыл бұрын
Nice explanation! What would be the time complexity of the solution? O(logN) ??
@rishenglian9959
@rishenglian9959 Жыл бұрын
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 Жыл бұрын
@@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)
@lasredchris
@lasredchris 3 жыл бұрын
at 11:56 Why do we do div = div / 100 and not div = div/10 ?
@mohammadal-abbasi6155
@mohammadal-abbasi6155 3 жыл бұрын
@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).
@Andre-rk1py
@Andre-rk1py 2 жыл бұрын
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
@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 Жыл бұрын
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
@ritiksingh2692
@ritiksingh2692 Жыл бұрын
can you give the same solution in java pls
@jakobleo3440
@jakobleo3440 3 жыл бұрын
wonderful video!
@sherrypan6029
@sherrypan6029 2 жыл бұрын
return str(x) == str(x) [::-1]
@sreedeepthichigurupati2824
@sreedeepthichigurupati2824 Жыл бұрын
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 7 ай бұрын
Ngl, but this is quite easy to understand. The code is short & precise, plus it works well. Thanks for sharing out the code
@user-xk2zy3ng1o
@user-xk2zy3ng1o Жыл бұрын
O(log10N) , right?
@pawankishorsingh
@pawankishorsingh 3 жыл бұрын
The "Problem Link" is wrong in your description. Please correct it.
@NeetCode
@NeetCode 3 жыл бұрын
sorry about that, fixed!
@Hetshah25
@Hetshah25 Жыл бұрын
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 Жыл бұрын
thanks man that was way more easier
@c1inward346
@c1inward346 Жыл бұрын
there is a follow up question: can you solve the problem without converting it into string?
@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 6 ай бұрын
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
@venkatbalachandra5965
@venkatbalachandra5965 Жыл бұрын
class Solution: def isPalindrome(self, x: int) -> bool: return (str(x)==str(x)[::-1])
@animelegaxy
@animelegaxy 2 жыл бұрын
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; }
@manikhanthkatti3448
@manikhanthkatti3448 3 жыл бұрын
First again ❤️
@asdasddas100
@asdasddas100 3 жыл бұрын
K ♥️
@NeetCode
@NeetCode 3 жыл бұрын
𝕟𝕚𝕔𝕖
@APudgyPanda96
@APudgyPanda96 Жыл бұрын
What a stupid problem
@bereketyisehak5584
@bereketyisehak5584 Жыл бұрын
lol
@peter-eh2oq
@peter-eh2oq 2 жыл бұрын
this is wrong
@pythonprospect532
@pythonprospect532 2 жыл бұрын
Why?
@DevMaster-13
@DevMaster-13 Жыл бұрын
Will this work? x_str = str(x) return x_str == x_str[::-1]
@licokr
@licokr 5 ай бұрын
the point is not to covert from integer to string
@akhmadillom
@akhmadillom Жыл бұрын
Thank you!
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 465 М.
Integer to Roman - Leetcode 12 - Python
9:43
NeetCode
Рет қаралды 69 М.
Мы сделали гигантские сухарики!  #большаяеда
00:44
А ВЫ УМЕЕТЕ ПЛАВАТЬ?? #shorts
00:21
Паша Осадчий
Рет қаралды 2 МЛН
PEDRO PEDRO INSIDEOUT
00:10
MOOMOO STUDIO [무무 스튜디오]
Рет қаралды 19 МЛН
LARGEST PALINDROMIC NUMBER | LEETCODE 2384 | PYTHON SOLUTION
14:56
Cracking FAANG
Рет қаралды 1,7 М.
9. Palindrome Number - Leetcode (Python)
4:00
Quoc Dat Phung
Рет қаралды 7 М.
Ugly Number - Leetcode 263 - Python
10:44
NeetCode
Рет қаралды 24 М.
Solving Wordle using information theory
30:38
3Blue1Brown
Рет қаралды 10 МЛН
Big-O Notation - For Coding Interviews
20:38
NeetCode
Рет қаралды 456 М.
The Problem with Time & Timezones - Computerphile
10:13
Computerphile
Рет қаралды 4 МЛН
The LeetCode Fallacy
6:08
NeetCode
Рет қаралды 483 М.
Coding a Web Server in 25 Lines - Computerphile
17:49
Computerphile
Рет қаралды 334 М.
5 Useful F-String Tricks In Python
10:02
Indently
Рет қаралды 299 М.