Plus One - Leetcode 66 - Python

  Рет қаралды 57,473

NeetCode

NeetCode

Күн бұрын

Пікірлер: 92
@sivakrishnaviru
@sivakrishnaviru 3 жыл бұрын
Love your work! Minor changes without reversing the digits . i = len(digits)-1 while i >= 0: if (digits[i] == 9): digits[i] = 0 else: digits[i] += 1 return digits i -= 1 return [1] + digits
@pauljones9150
@pauljones9150 2 жыл бұрын
THIS IS SOME CRAZY GOOD CODE
@pauljones9150
@pauljones9150 2 жыл бұрын
@@heagandev Lemme know if this is a thing. I'd be interested to join
@pratiek544
@pratiek544 2 жыл бұрын
thank you brother
@markolainovic
@markolainovic Жыл бұрын
/salute
@Pratik-tk6ts
@Pratik-tk6ts Жыл бұрын
excellent
@danielsun716
@danielsun716 Жыл бұрын
for i in range(len(digits) - 1, -1, -1): if digits[i] == 9: digits[i] = 0 else: digits[i] += 1 return digits return [1] + digits
@shakhzod_shermatov
@shakhzod_shermatov 3 ай бұрын
The best solution ever🔥
@jeremyvidaurri
@jeremyvidaurri 2 жыл бұрын
Interesting solution. Here's what I did, class Solution: def plusOne(self, digits: List[int]) -> List[int]: n = len(digits) - 1 carry = 1 while (carry and n != -1): carry = (digits[n] + 1) // 10 digits[n] = (digits[n] + 1) % 10 n -= 1 if carry: digits.insert(0,1) return digits
@licokr
@licokr 10 ай бұрын
I wasn't planning to look up the solution of this problem. But I like you and watched the video then I found out you break out the loop when it doesn't need to using the `one` variable, which I didn't. my loop always iterates until the end. Wow... The ability of figuring out you exactly have todo is really awesome. Thank you so much for uploading great videos!
@saran703
@saran703 3 жыл бұрын
why dont we convert it [1, 2, 3] to normal interger like 123 and add one to it 124 and then we return it into array [1, 2, 4] !
@NeetCode
@NeetCode 3 жыл бұрын
Yeah, I think you're right. Only issue I can think of is, what if the integer is too large for 32 bits, that wouldn't be a problem in python but could be in other languages.
@jonaskhanwald566
@jonaskhanwald566 3 жыл бұрын
s = [str(i) for i in digits] res = int("".join(s)) print(res+1) output = [int(x) for x in str(res+1)] return output we can do this way. But its not logical way to approach problems
@farjanashaik9601
@farjanashaik9601 2 жыл бұрын
yes, I tried this way there it will work nut the prob is time will be O(2n) when compared to the efficient approch
@samer820
@samer820 2 жыл бұрын
@@farjanashaik9601 O(2n) is still O(n) though.
@jarvispotter6125
@jarvispotter6125 10 ай бұрын
@@jonaskhanwald566p
@geekydanish5990
@geekydanish5990 2 жыл бұрын
without reversing class Solution: def plusOne(self, digits: List[int]) -> List[int]: carry,i = 1,len(digits)-1 while carry: if i >= 0: if digits[i] == 9: digits[i] = 0 else: digits[i] += 1 carry = 0 elif i == -1: digits = [carry]+digits carry = 0 i -=1 return digits
@danielbzhang3280
@danielbzhang3280 Жыл бұрын
Thanks! This is a better solution!
@andymartinez6732
@andymartinez6732 Жыл бұрын
Here's my solution which uses recursion, lmk what y'all think: class Solution: def plusOne(self, digits: List[int]) -> List[int]: if not digits: return [1] if digits[-1] != 9: digits[-1] += 1 return digits return self.plusOne(digits[:-1]) + [0]
@Ben_in_4k
@Ben_in_4k Жыл бұрын
nice explanation didnt think about reversing the list but now i have that in the toolbag
@staazbeats
@staazbeats 3 жыл бұрын
your solutions are the best, thanks
@DabhouMalataj
@DabhouMalataj Жыл бұрын
Using recursion, without reversing, & any loop. class Solution: n = 0 def plusOne(self, digits: List[int]) -> List[int]: if digits[-1 - self.n] == 9: digits[-1 - self.n] = 0 self.n += 1 if (len(digits) - self.n)
@user-qg7lb1jx8b
@user-qg7lb1jx8b 8 ай бұрын
i don't know how to name my 'carry' variable so I'll call it one haha
@barnoma-soz
@barnoma-soz 2 жыл бұрын
simple way (no reversing) def plus_one(arr): i = len(arr)-1 while i >= 0: if arr[i] < 9: arr[i] += 1 break else: arr[i] = 0 i -= 1 if arr[0] == 0: arr.insert(0,1) return arr
@rddcol
@rddcol 2 жыл бұрын
lol doesnt work
@junjason4114
@junjason4114 2 жыл бұрын
This is my solution, iterate from end to start, I think it is easier to understand, hope it can help. class Solution: def plusOne(self, digits: List[int]) -> List[int]: carry = 1 for i in range(len(digits) - 1, -1, -1): digit = digits[i] digits[i] = (digit + carry) % 10 carry = (digit + carry) // 10 if carry: digits.insert(0, carry) return digits
@MohamedMagdy-00
@MohamedMagdy-00 2 жыл бұрын
Same In JS/TS function plusOne(digits: number[]): number[] { for(let i = digits.length - 1; i >= 0; i--) { const num = digits[i]; const remainder = (num+1) % 10; digits[i] = remainder; if(Math.trunc((num + 1) / 10) === 0) return digits; } digits.unshift(1); return digits; };
@prestoX
@prestoX Жыл бұрын
Isn't reversing the array O(n) operation internally?
@mounikadontha
@mounikadontha 8 ай бұрын
class Solution: def plusOne(self, digits: List[int]) -> List[int]: integer = int(''.join(map(str, digits))) integer += 1 return [int(digit) for digit in str(integer)]
@gamerofthegame6303
@gamerofthegame6303 5 ай бұрын
i think his code might be a bit confusing at first (my onpinion), so i tried to simplify the code based on his solution, here's the code: digits = digits[::-1] one, i = 1, 0 while i < len(digits) and one: if digits[i] == 9: digits[i] = 0 else: digits[i] += one one = 0 i += 1 if one: digits.append(one) one = 0 return digits[::-1]
@mahdiranjbar3569
@mahdiranjbar3569 5 ай бұрын
The space complexity of your algorithm is actually O(n) rather than O(1), because the digits[::-1] operation creates a copy of the list.
@chrisholland6366
@chrisholland6366 11 ай бұрын
Interesting. Thought of it in a different way, haha goes to show there is definitely more than one valid way of doing these. class Solution(object): def plusOne(self, digits): idx = len(digits) - 1 while True: if digits[idx] < 9: digits[idx] = digits[idx] + 1 return digits elif idx == 0: digits[idx] = 1 digits.append(0) return digits else: digits[idx] = 0 idx -= 1
@mohammednasser199
@mohammednasser199 2 жыл бұрын
This was the first answer that popped into my mind. return [int(c) for c in str(int("".join([str(c) for c in digits])) + 1 )]
@etchris
@etchris 3 жыл бұрын
Would something like a pointer work as well? Like if we start by pointing at the end of the list While-loop while p > -1. If a digit at the pointer is less then 9 then we add one to it return the digit list. If the digit at the pointer is 9, we set it to 0 and decrement the pointer. If we make to the end of the list and still haven't found a digit less than 9, then we just return [1] + digits.
@roshanzameer5020
@roshanzameer5020 2 жыл бұрын
i = len(digits) -1 while True: if i >= 0: if digits[i] == 9: digits[i] = 0 else: digits[i] += 1 return digits else: digits.insert(0, 1) return digits i -= 1
@aldrinjenson
@aldrinjenson 2 жыл бұрын
def plusOne(self, digits: List[int]) -> List[int]: p = len(digits) - 1 while True: if p == -1: digits = [1] + digits break if digits[p] is not 9: digits[p] += 1 break else: digits[p] = 0 p -= 1 return digits
@NHCS-ShreyasChaudhary
@NHCS-ShreyasChaudhary Жыл бұрын
n=len(digits) for i in range(n-1,-1,-1): if digits[i] < 9: digits[i] += 1 return digits else: digits[i]=0 return [1] + [0]*n
@KingFuYouTube
@KingFuYouTube 2 жыл бұрын
For my language which is Kotlin it takes in an array and return an array. I wonder how you would do it with an array. I did it but the space complexity is like O(n).
@CostaKazistov
@CostaKazistov 2 жыл бұрын
class Solution { fun plusOne(digits: IntArray): IntArray { for (i in digits.indices.reversed()) { if (digits[i] < 9) { digits[i]++ return digits } digits[i] = 0 } return intArrayOf(1) + digits } }
@KingFuYouTube
@KingFuYouTube 2 жыл бұрын
@@CostaKazistov Thank you so much it works!
@Famelhaut
@Famelhaut Жыл бұрын
1 LINE python solution: class Solution: def plusOne(self, digits: List[int]) -> List[int]: return [int(digit) for digit in str(int("".join(map(lambda x: str(x), digits))) + 1)]
@danishmehmood6110
@danishmehmood6110 6 ай бұрын
bro in javascript this is so simple , it also gets accepted in leetcode var plusOne = function(digits) { let inputinnumber = Number(digits.join("")) let addition = inputinnumber+1 let result = String(addition).split('') result = result.map(val=>{return parseInt(val)}) return result };
@ulinchen1910
@ulinchen1910 2 жыл бұрын
my solution with recursive function: class Solution: def plusOne(self, digits: List[int]) -> List[int]: k = len(digits) - 1 def check(k, digits): if k == 0 and digits[k] == 9: digits[k] = 0 digits.insert(k, 1) return digits if digits[k] < 9: digits[k] += 1 return digits else: digits[k] = 0 return check(k-1,digits) return check(k,digits)
@sharpesthawk
@sharpesthawk Жыл бұрын
My Approach (used try-except also didnt need CARRY or REVERSING array): i = -1 try: while True: if digits[i] != 9: digits[i] += 1 return digits digits[i] = 0 i -= 1 except: digits.insert(0, 1) return digits
@yuanfeng4843
@yuanfeng4843 Жыл бұрын
class Solution: def plusOne(self, digits: List[int]) -> List[int]: n = len(digits) for i in range(n-1, -1, -1): if digits[i]
@dallasmilanista8291
@dallasmilanista8291 3 жыл бұрын
Wouldn't the while loop terminate irrespective of where it is in the iteration if one is equal to 0 in the nested else condition?
@roshanzameer5020
@roshanzameer5020 2 жыл бұрын
You have to add 1 to an integer element only once. And when that's done, you should break out of loop and return.
@venky3639
@venky3639 3 жыл бұрын
Great explanation 🎉
@104-saitejagurram8
@104-saitejagurram8 9 ай бұрын
class Solution: def plusOne(self, digits: List[int]) -> List[int]: num = 0 for digit in digits: num = num * 10 + digit num=num+1 return [int(digit) for digit in str(num)]
@raskovnic
@raskovnic 2 жыл бұрын
my solution class Solution: def plusOne(self, digits: List[int]) -> List[int]: return self.addOne(digits, len(digits) - 1) def addOne(self, digits, index): if index == 0 and digits[index] == 9: digits.insert(0, 1) digits[1] = 0 return digits if digits[index] == 9: digits[index] = 0 self.addOne(digits, index-1) else: digits[index] += 1 return digits
@chamikaonyt
@chamikaonyt 2 жыл бұрын
def add(digits): number = "" for i in digits: number += str(i) number = int(number) + 1 output = [int(i) for i in str(number)] return output
@liamsism
@liamsism 2 жыл бұрын
without reverse and a while loop: def plusOne(self, digits: List[int]) -> List[int]: mem = 1 for i in range(len(digits) - 1, -1, -1): digits[i] += mem mem = digits[i] // 10 digits[i] %= 10 if mem: digits = [mem] + digits return digits
@ARkhan-xw8ud
@ARkhan-xw8ud 6 ай бұрын
this is my solution for the problem it's more simple and easily understandable class Solution: def plusOne(self, digits: List[int]) -> List[int]: a = '' " for n in digits: a += str(n) b = int(a) + 1 return [int(x) for x in str(b)]
@DavidWeissProgramming
@DavidWeissProgramming Жыл бұрын
Check out this solution. Short and succinct: class Solution: def plusOne(self, digits: List[int]) -> List[int]: for i in range(len(digits) - 1, -1, -1): if digits[i] != 9: digits[i] += 1 return digits digits[i] = 0 digits[0] = 1 return digits + [0]
@hwang1607
@hwang1607 8 ай бұрын
Am I not supposed to do something like this: class Solution: def plusOne(self, digits: List[int]) -> List[int]: temp = "".join(str(x) for x in digits) temp = int(temp) + 1 return [int(x) for x in str(temp)]
@Iam2MAS
@Iam2MAS Жыл бұрын
this my code class Solution: def plusOne(self, digits: List[int]) -> List[int]: i = len(digits) -1 while i >= 0: if digits[i] < 9: digits[i] += 1 break else: digits[i] = 0 i-= 1 if digits[0] == 0: digits = [1] + [0 for i in range(len(digits))] return digits
@mubashirtanwar8674
@mubashirtanwar8674 Жыл бұрын
This is my solution: Will i ever be good at DSA if i work around problems like this class Solution(object): def plusOne(self, digits): sum = 0 for i in range(0,len(digits)): sum += digits[i]*10**(len(digits)-1-i) sum +=1 count = 0 temp = sum while temp != 0: temp //= 10 count += 1 newdigits = [0]*count newdigits[0] = (sum//10**abs(count-1)) rem = (sum//10**abs(count-1)) for i in range(1,count) : newdigits[i] = (sum//10**abs(count-i-1)) - rem*10 rem = (sum//10**abs(count-i-1)) return newdigits
@nikitasinha8181
@nikitasinha8181 2 жыл бұрын
Thank you so much sir
@samyriache
@samyriache 4 ай бұрын
my solution class Solution: def plusOne(self, digits: List[int]) -> List[int]: b ="" c =[] l = len(digits) for i in range(len(digits)) : b += str(digits[i]) b_num = int(b) b_num += 1 b_num_string = str(b_num) for j in range (len(b_num_string)) : c.append(int(b_num_string[j])) return c
@ombothre2350
@ombothre2350 6 ай бұрын
T: O(n) S: O(1) class Solution: def plusOne(self, digits: List[int]) -> List[int]: i = len(digits) - 1 while digits[i] == 9 and i >= 0: if i == 0 and digits[i] == 9: digits[i] = 0 return [1] + digits digits[i] = 0 i -= 1 digits[i] += 1 return digits
@MrCCronyn
@MrCCronyn 7 ай бұрын
Here's another way: ``` class Solution: def plusOne(self, digits: List[int]) -> List[int]: for i, v in reversed(list(enumerate(digits))): if v == 9: digits[i] = 0 else: digits[i] += 1 return digits digits.insert(0, 1) return digits ```
@miradorteton125
@miradorteton125 3 жыл бұрын
You are a genius
@vinay22914125
@vinay22914125 2 жыл бұрын
looks like you are making more complex. You can just do in one iteration. No need reverse. class Solution { public int[] plusOne(int[] digits) { boolean breakCheck = false; // repeat loop until reach the number which is not equals to 9. for (int i=digits.length-1;i>=0 && !breakCheck;i--) { if (digits[i] != 9) { digits[i] = digits[i]+1; breakCheck = true; } else { digits[i] = 0; } } if (digits[0] == 0) { int[] results = new int[digits.length+1]; results[0] = 1; return results; } return digits; } }
@aurkom
@aurkom 7 ай бұрын
``` def plusOne(self, digits: List[int]) -> List[int]: idx = len(digits)-1 while idx >= 0: if digits[idx] != 9: digits[idx] += 1 return digits else: digits[idx] = 0 idx -= 1 return [1] + digits ```
@prashantgupta7803
@prashantgupta7803 3 жыл бұрын
Thanks!
@richardnorth1881
@richardnorth1881 2 жыл бұрын
Easter egg 5:42 dogo found
@SharmaTushar1-yt
@SharmaTushar1-yt Жыл бұрын
I don't get it. I looked up the solutions and everyone did the same thing. Why don't just make a digit? class Solution: def plusOne(self, digits: List[int]) -> List[int]: n = 0 for digit in digits: n *= 10 n += digit n += 1 op = [] while n!=0: op.append(n%10) n = n//10 return op[::-1] It will have extra space anyways when we want to append the carry (especially in languages like Java where array's length is immutable) I get it maybe the above solution is slightly better for arrays without carry but overall they both have the same worst case time complexity.
@ivanstoykov7151
@ivanstoykov7151 2 жыл бұрын
class Solution: def plusOne(self, digits: List[int]) -> List[int]: num = int("".join(map(str, digits))) + 1 return [x for x in str(num)]
@ibrahimabdul-qadir2091
@ibrahimabdul-qadir2091 2 жыл бұрын
bruh how
@gubbu8352
@gubbu8352 2 жыл бұрын
This code does'nt work when digits has [9] only..!!!!
@tlz124
@tlz124 4 ай бұрын
That's funny cuz Leetcode list digits = [9] as an edge case and I was about to comment that I wish Leetcode would show all the edge cases to test
@vmedisetty
@vmedisetty 2 жыл бұрын
I'm a programming newbie. This was my solution: class Solution: def plusOne(self, digits: List[int]) -> List[int]: rev_list = digits[::-1] final_list = [] value = 0 for i in range(len(digits)): j = 10**i value += rev_list[i]*j value+=1 value = str(value) for i in range(len(value)): final_list.append(int(value[i])) return(final_list)
@chiraagpala3243
@chiraagpala3243 3 жыл бұрын
could you do 30. Substring with Concatenation of All Words sometime in the near future please and thank you
@shreyghai8508
@shreyghai8508 2 жыл бұрын
u could totally do that, convert the list into string, then convert to an integer, and add one to it, then throw each digit in a list, but that way is kinda hard coding it and is not the intended way to solve the problem!
@zomgneedaname
@zomgneedaname 2 жыл бұрын
the number of dislikes on this question 🤣
@tachyon7777
@tachyon7777 9 ай бұрын
Seriously you had to explain why 9+1=10 can't be put in the last position? Really? Also one=0 is likely the worst line of code ever written. I know this is silly and you explained as being just lazy, but why though in a youtube video? You could just name it carry.
@symbol767
@symbol767 3 жыл бұрын
This is not an easy problem, leetcode is on drugs
@NeetCode
@NeetCode 3 жыл бұрын
Agreed lol
@TheYoutubeJuan
@TheYoutubeJuan 2 жыл бұрын
I had a different approach look exponent = 0 number = 0 i = len(digits) - 1 while i >= 0 : number += (digits[i] * (10**exponent)) exponent +=1 i -= 1 number += 1 arr = [] while number > 0: x = number % 10 arr.insert(0,x) number = number // 10 return arr
@nikhil_a01
@nikhil_a01 Жыл бұрын
It's definitely an Easy problem. Took me 8.5 minutes. NeetCode's solution is a bit harder to come up with. But you can literally just add 1 to the first digit, and then propagate the carry, adding it to each digit: class Solution: def plusOne(self, digits: List[int]) -> List[int]: result = [] carry = 1 for digit in reversed(digits): new_digit = digit + carry if new_digit == 10: result.append(0) carry = 1 else: result.append(new_digit) carry = 0 if carry != 0: result.append(carry) result.reverse() return result Or you can even replace that if-else with result.append(new_digit % 10) carry = new_digit // 10 which is much nicer looking but may confuse some people.
@niko-l-
@niko-l- 3 жыл бұрын
Thanks for your videos. Not sure about Python, in JS and C-family we can use do-while language constriction with backward iteration. At the end if carry isn't 0 unshift '1' to the array. Complexity is still same just without array reversions.
@prathameshkulkarni4176
@prathameshkulkarni4176 Жыл бұрын
I just constructed the original number, added the one and then again deconstructed the number to be inserted in the array. class Solution: def plusOne(self, digits: List[int]) -> List[int]: x = len(digits) - 1 num = 0 for i in digits: num = num + (i * 10**x) x -= 1 num += 1 num=str(num) new=[] for i in num: new.append(int(i)) return new
@MandolinSashaank
@MandolinSashaank Ай бұрын
return [int(d) for d in str(int("".join(map(str, digits))) + 1)]
@tomato2699
@tomato2699 Жыл бұрын
Braindead python solution - 2 passes - O(N) time, O(1) space. Create current sum --> add 1 to get new sum --> mutate list to reflect new sum, but before that handle edge case by checking if all digits are nines, if all digits are nines, add an additional array slot class Solution: def plusOne(self, digits: List[int]) -> List[int]: total_sum = 0 is_all_nines = True num_iterations_passed = 0 for i in range(len(digits)-1, -1, -1): if digits[i] != 9: is_all_nines = False actual_digit = 10**num_iterations_passed * digits[i] total_sum += actual_digit num_iterations_passed += 1 new_sum = total_sum + 1 if is_all_nines: placeholder_num = 0 digits.append(placeholder_num) for i in range(len(digits)-1, -1, -1): new_actual_digit = new_sum%10 digits[i] = new_actual_digit new_sum //= 10 return digits
@festusmuldoon
@festusmuldoon 6 ай бұрын
return [int(x) for x in list(str(int("".join([str(x) for x in digits])) + 1))]
@DabhouMalataj
@DabhouMalataj Жыл бұрын
Using recursion, without reversing, & any loop. class Solution: n = 0 def plusOne(self, digits: List[int]) -> List[int]: if digits[-1 - self.n] == 9: digits[-1 - self.n] = 0 self.n += 1 if (len(digits) - self.n)
LeetCode was HARD until I Learned these 15 Patterns
13:00
Ashish Pratap Singh
Рет қаралды 733 М.
Try this prank with your friends 😂 @karina-kola
00:18
Andrey Grechka
Рет қаралды 9 МЛН
Don’t Choose The Wrong Box 😱
00:41
Topper Guild
Рет қаралды 62 МЛН
Une nouvelle voiture pour Noël 🥹
00:28
Nicocapone
Рет қаралды 9 МЛН
Cat mode and a glass of water #family #humor #fun
00:22
Kotiki_Z
Рет қаралды 42 МЛН
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 783 М.
Contiguous Array - Leetcode 525 - Python
15:41
NeetCodeIO
Рет қаралды 32 М.
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 490 М.
Pascal's Triangle - Leetcode 118 - Python
8:41
NeetCode
Рет қаралды 103 М.
Mastering Dynamic Programming - How to solve any interview problem (Part 1)
19:41
I Solved 100 LeetCode Problems
13:11
Green Code
Рет қаралды 310 М.
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Codebagel
Рет қаралды 341 М.
My Brain after 569 Leetcode Problems
7:50
NeetCode
Рет қаралды 2,7 МЛН
Minimize XOR - Leetcode 2429 - Python
12:17
NeetCodeIO
Рет қаралды 6 М.
Try this prank with your friends 😂 @karina-kola
00:18
Andrey Grechka
Рет қаралды 9 МЛН