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
@pauljones91502 жыл бұрын
THIS IS SOME CRAZY GOOD CODE
@pauljones91502 жыл бұрын
@@heagandev Lemme know if this is a thing. I'd be interested to join
@pratiek5442 жыл бұрын
thank you brother
@markolainovic Жыл бұрын
/salute
@Pratik-tk6ts Жыл бұрын
excellent
@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_shermatov3 ай бұрын
The best solution ever🔥
@jeremyvidaurri2 жыл бұрын
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
@licokr10 ай бұрын
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!
@saran7033 жыл бұрын
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] !
@NeetCode3 жыл бұрын
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.
@jonaskhanwald5663 жыл бұрын
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
@farjanashaik96012 жыл бұрын
yes, I tried this way there it will work nut the prob is time will be O(2n) when compared to the efficient approch
@samer8202 жыл бұрын
@@farjanashaik9601 O(2n) is still O(n) though.
@jarvispotter612510 ай бұрын
@@jonaskhanwald566p
@geekydanish59902 жыл бұрын
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 Жыл бұрын
Thanks! This is a better solution!
@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 Жыл бұрын
nice explanation didnt think about reversing the list but now i have that in the toolbag
@staazbeats3 жыл бұрын
your solutions are the best, thanks
@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-qg7lb1jx8b8 ай бұрын
i don't know how to name my 'carry' variable so I'll call it one haha
@barnoma-soz2 жыл бұрын
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
@rddcol2 жыл бұрын
lol doesnt work
@junjason41142 жыл бұрын
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-002 жыл бұрын
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 Жыл бұрын
Isn't reversing the array O(n) operation internally?
@mounikadontha8 ай бұрын
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)]
@gamerofthegame63035 ай бұрын
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]
@mahdiranjbar35695 ай бұрын
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.
@chrisholland636611 ай бұрын
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
@mohammednasser1992 жыл бұрын
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 )]
@etchris3 жыл бұрын
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.
@roshanzameer50202 жыл бұрын
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
@aldrinjenson2 жыл бұрын
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 Жыл бұрын
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
@KingFuYouTube2 жыл бұрын
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).
@CostaKazistov2 жыл бұрын
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 } }
@KingFuYouTube2 жыл бұрын
@@CostaKazistov Thank you so much it works!
@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)]
@danishmehmood61106 ай бұрын
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 };
@ulinchen19102 жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
class Solution: def plusOne(self, digits: List[int]) -> List[int]: n = len(digits) for i in range(n-1, -1, -1): if digits[i]
@dallasmilanista82913 жыл бұрын
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?
@roshanzameer50202 жыл бұрын
You have to add 1 to an integer element only once. And when that's done, you should break out of loop and return.
@venky36393 жыл бұрын
Great explanation 🎉
@104-saitejagurram89 ай бұрын
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)]
@raskovnic2 жыл бұрын
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
@chamikaonyt2 жыл бұрын
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
@liamsism2 жыл бұрын
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-xw8ud6 ай бұрын
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 Жыл бұрын
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]
@hwang16078 ай бұрын
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 Жыл бұрын
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 Жыл бұрын
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
@nikitasinha81812 жыл бұрын
Thank you so much sir
@samyriache4 ай бұрын
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
@ombothre23506 ай бұрын
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
@MrCCronyn7 ай бұрын
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 ```
@miradorteton1253 жыл бұрын
You are a genius
@vinay229141252 жыл бұрын
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; } }
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.
@ivanstoykov71512 жыл бұрын
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-qadir20912 жыл бұрын
bruh how
@gubbu83522 жыл бұрын
This code does'nt work when digits has [9] only..!!!!
@tlz1244 ай бұрын
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
@vmedisetty2 жыл бұрын
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)
@chiraagpala32433 жыл бұрын
could you do 30. Substring with Concatenation of All Words sometime in the near future please and thank you
@shreyghai85082 жыл бұрын
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!
@zomgneedaname2 жыл бұрын
the number of dislikes on this question 🤣
@tachyon77779 ай бұрын
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.
@symbol7673 жыл бұрын
This is not an easy problem, leetcode is on drugs
@NeetCode3 жыл бұрын
Agreed lol
@TheYoutubeJuan2 жыл бұрын
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 Жыл бұрын
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-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 Жыл бұрын
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Ай бұрын
return [int(d) for d in str(int("".join(map(str, digits))) + 1)]
@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
@festusmuldoon6 ай бұрын
return [int(x) for x in list(str(int("".join([str(x) for x in digits])) + 1))]
@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)