Add Binary - Leetcode 67 - Python

  Рет қаралды 64,753

NeetCode

NeetCode

Күн бұрын

Пікірлер: 88
@NeetCode
@NeetCode 3 жыл бұрын
✏️ Have problem suggestions you would like me to solve? Feel free to comment them below :~)
@vijaychikkannavar5060
@vijaychikkannavar5060 2 жыл бұрын
last line should be return res[::-1] to reverse it back to original format
@sagargulati639
@sagargulati639 2 жыл бұрын
@@vijaychikkannavar5060 Yes you are right.
@DeeBall
@DeeBall 2 жыл бұрын
@@vijaychikkannavar5060 no
@subhashreesahoo6125
@subhashreesahoo6125 Жыл бұрын
Diagonal Matrix problem
@aaa_1711
@aaa_1711 9 ай бұрын
Why use ord?? Since we know it can either be 0 or 1. Why not just a string comparison and assign. Like, if it's "0", then digitA is 0, else 1 Same for digitB Good implementation though
@shakhzod_shermatov
@shakhzod_shermatov Ай бұрын
Your way of speaking is astonishing to be honest, without repetition, concise, and very structured. It's difficult even for native speakers to explain at this level, I guess. Thanks for sharing your knowledge. Huge respect for you! You deserve it.❤
@yoshi4980
@yoshi4980 3 жыл бұрын
an easy problem that can get boggled down in edge cases, really like some the tricks you used. great video as always!
@srinadhp
@srinadhp 3 жыл бұрын
Love the way you write the code. Concise. Love the loop of max of lengths. Great explanation as usual
@sunnilabeouf
@sunnilabeouf 3 жыл бұрын
Can't we just use int(a[i]) to cast it to an integer?
@NeetCode
@NeetCode 3 жыл бұрын
Yeah, you're right, I just remembered that. Thanks for pointing it out.
@surbhirohilla5139
@surbhirohilla5139 2 жыл бұрын
I was thinking the same and thougth what's the meaning of ord(0) which I can't understand😂lol, it was a mistake
@stove.d
@stove.d 2 жыл бұрын
@@surbhirohilla5139 ord() converts each string value to the integer representation of the unicode value (i.e. ASCII table), so subtracting ord("0") from ord("n") where 'n' is any number 0-9 will return that number. In ASCII, "0"=48 and "9"=57, so in that case `ord("9") - ord("0")` = 57 - 48 = 9
@muzikjay
@muzikjay 2 жыл бұрын
"Let's go back to elementary school and add these together. What happens when we add 1 and 1?.....0?" 😂
@EmilyHopeGrove
@EmilyHopeGrove 9 ай бұрын
this...
@sanjayp7027
@sanjayp7027 3 жыл бұрын
how is this a easy problem :|
@LetCode96666
@LetCode96666 5 ай бұрын
It's an easy but long problem for me. I solved it my way without any math 😅
@strawberriesandcream2863
@strawberriesandcream2863 2 жыл бұрын
thanks, you're a lifesaver when it comes to leetcode
@rachnaramkumar
@rachnaramkumar 2 жыл бұрын
Isn't the time complexity quadratic since the addition of the 'char' string to the 'res' string copies all the contents and creates a new string for every loop since strings in python are immutable?
@ohyash
@ohyash 2 жыл бұрын
Yes. I'd append to the result string. And then reverse the string once in the end. Or push the result values to a stack and then form a result string in the end popping out from the stack.
@airysm
@airysm 3 жыл бұрын
Hi at 5:10, couldnt you use int() instead of ord() to cast the char?
@blaiserodrigues2990
@blaiserodrigues2990 3 жыл бұрын
Yes. you can.
@akhileshb5859
@akhileshb5859 2 жыл бұрын
You are a good teacher. Keep up the good work. Thank you!
@beldam94
@beldam94 2 жыл бұрын
This code is simply beautiful. Thanks.
@BurhanAijaz
@BurhanAijaz Жыл бұрын
we can use the same code for the question : leetcode 413(Add strings),just replace 2 by 10
@BurhanAijaz
@BurhanAijaz Жыл бұрын
code: class Solution: def addStrings(self, a: str, b: str) -> str: ans="" carry=0 a,b=a[::-1],b[::-1] for i in range(max(len(a),len(b))): digitA = ord(a[i])-ord('0') if i
@vikasz2
@vikasz2 Жыл бұрын
def addBinary(self, a: str, b: str) -> str: a = int(a,2) b = int(b,2) res = a+b return bin(res)[2:]
@suriya113
@suriya113 2 ай бұрын
Bro can you explain to me this code please
@sagargulati639
@sagargulati639 2 жыл бұрын
The returned res should be reversed to get the original output. return res[::-1]
@pranavsharma7479
@pranavsharma7479 2 жыл бұрын
nah see how is appending
@sriramkarthikakella2033
@sriramkarthikakella2033 Жыл бұрын
For converting it to integer, can we not do int(a[i]) and int(b[i]) instead of ord(a[i])-ord("0") and ord(b[i])-ord("0")?
@fadsa342
@fadsa342 Жыл бұрын
that worked for me in my solution
@cedriczhang6129
@cedriczhang6129 12 күн бұрын
def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ # Convert binary strings to integers num1 = int(a, 2) num2 = int(b, 2) # Compute the sum result = num1 + num2 # Convert the sum back to binary and remove the '0b' prefix return bin(result)[2:]
@MaxFung
@MaxFung Жыл бұрын
Youre an amazing teacher mr. neet!
@clara8490
@clara8490 3 жыл бұрын
Amazing video and nice explanation!!!
@karthikkumaresan1091
@karthikkumaresan1091 3 жыл бұрын
What is the time complexity of the string concats in python(eg. char + res in the example above)
@XzcutioneR2
@XzcutioneR2 Жыл бұрын
Why not just do bin(int(a, 2) + int(b, 2))[2:] ?
@seenumadhavan4451
@seenumadhavan4451 Жыл бұрын
There is no time complexity and space complexity mentioned in the problem. This should be fine i guess
@ShubhamShekhar-cm6rs
@ShubhamShekhar-cm6rs Жыл бұрын
Convert the array into non non-decreasing array by replacing elements with its subarray sum if necessary. for example, input=[3, 8, 5, 2, 10], output=[3,8,17] input=[1,2,3,4,5],output=[1,2,3,4,5] input=[5,4,3,2,1],output=[5,10] input=[],output=[] Please solve this problem.
@RohanVenkateshGupta
@RohanVenkateshGupta 2 жыл бұрын
Wonderful Explanation 👍👍👍
@gagansuneja7029
@gagansuneja7029 2 жыл бұрын
we could have appended 0* (a.size - b.size) to the shorter string, saving time in reversal of both the strings. Later reversing the final string
@andrewromanenkov6929
@andrewromanenkov6929 3 жыл бұрын
Answer in 2 lines of code: c = bin(int(a,2) + int(b,2)) return c[2:]
@willd9807
@willd9807 2 жыл бұрын
print(eval())
@ohyash
@ohyash 2 жыл бұрын
Interviewer: _Pikachu face_
@Levelord92
@Levelord92 2 жыл бұрын
yeah, put 9223372036854775807 and 9223372036854775807 as summands and see what happens, genius
@malh851
@malh851 11 ай бұрын
Great Explanation! Might be cleaner to use the divmod() function instead of % and //. Eg. char, carry = divmod(total, 2) res = str(char) + res
@triplestrikee875
@triplestrikee875 3 жыл бұрын
Very well explained, but don't we need to return res[::-1]?
@triplestrikee875
@triplestrikee875 3 жыл бұрын
Never mind, I thought res = char + res in the loop is same as res += char. My bad.
@ohyash
@ohyash 2 жыл бұрын
@@triplestrikee875 not the same.. Prepending char in the beginning of the string makes python have to copy all the result values everytime. It's better to append chars throughout and then reverse before returning in the end
@torontonian77
@torontonian77 2 жыл бұрын
one thing I never knew before is that you can use f-strings to convert int to binary. def binary_conversion(num): return f'{num:b}' so binary_conversion(1000) will get a result of 1111101000
@RobertMcHalffey
@RobertMcHalffey Жыл бұрын
Python solution converted to JavaScript: var addBinary = function(a, b) { let totalSum = ''; let carry = 0; a = a.split('').reverse().join(''); b = b.split('').reverse().join(''); for (let i = 0; i < Math.max(a.length, b.length); i++){ const digitA = parseInt(i < a.length ? a[i] : 0); const digitB = parseInt(i < b.length ? b[i] : 0); const total = digitA + digitB + carry; const currentSum = total % 2; totalSum = currentSum + totalSum; carry = Math.floor(total / 2); } return carry ? 1 + totalSum : totalSum; };
@jankeshchakravarthy9389
@jankeshchakravarthy9389 Жыл бұрын
Nice explanation. Did you forget to reverse the result??
@ShivangiSingh-wc3gk
@ShivangiSingh-wc3gk 2 ай бұрын
I was thinking that the interviewer would want the bit manipulation solution for this
@geraldakorli
@geraldakorli 11 ай бұрын
Why didn't you use int function on the values a[i] and b[i]?
@antoinenijhuis450
@antoinenijhuis450 10 ай бұрын
Why are we usig "ord" instead of "int(str)" ?? @NeetCode
@alexgolomb363
@alexgolomb363 10 ай бұрын
Thank you for explaining what happens when you add "11" and "11". I was completely lost but not anymore thanks to you!
@Salah-YT
@Salah-YT 2 жыл бұрын
thank u bro it is done and passed but I don't understand what I'm doing so what should I do to be better in Leetcode for everything I must find a tutorial so the tutorial killing me bro please help me out so more than a year I did a lot of HTML CSS javascript and 1000 of course and now python, why I can't, make a project and why I can't solve one easy problem in Leetcode or code war so I don't know bro and I fill I know everything but I can't code by my self must follow someone bro thx
@willd9807
@willd9807 2 жыл бұрын
I havent run the code, but did you get a character short each time from your reversing method. a,b = reversed(a), reversed(b)
@mruduladdipalli5417
@mruduladdipalli5417 2 жыл бұрын
I implemented same approach for Dart, it gave Time Limit Exceeded, but for java it worked :(
@aaa_1711
@aaa_1711 9 ай бұрын
Why use ord?? Since we know it can either be 0 or 1. Why not just a string comparison and assign. Like, if it's "0", then digitA is 0, else 1 Same for digitB Good implementation though
@abisheknair3545
@abisheknair3545 2 жыл бұрын
int(a[i]) worked succesfully. so why did u use ord?
@duncanproctor7160
@duncanproctor7160 2 жыл бұрын
Why not just pad the shorter string with leading zeros?
@Levelord92
@Levelord92 2 жыл бұрын
interesting...
@fadsa342
@fadsa342 Жыл бұрын
that's what I did. I guess technically by padding you're taking up more space and the operation isn't free since you're creating a new string and iterating over the existing one.
@mehmetnadi8930
@mehmetnadi8930 2 жыл бұрын
is it normal to find "easy" questions hard? i mean i don't think most of the easy question are actually easy ngl :///
@NeetCode
@NeetCode 2 жыл бұрын
Absolutely, I struggled a lot with easy questions when I started. Eventually you will make progress!
@pcccmn
@pcccmn 2 жыл бұрын
yeah same feeling. I'm doing the Blind 75 Easy questions. Out of 20 questions I have attempted, I don't know how solve any :) It is what it is. I'm not smart, but that's ok. Traditional hardwork and repetition has never failed me. Good luck to you bro, for whatever reasons you're studying DSA.
@huhuboss8274
@huhuboss8274 2 жыл бұрын
@@pcccmn how is it going? Did you improve?
@chamahge3518
@chamahge3518 4 ай бұрын
i have a question for that carry = total//2 what if we add only 1 and 0 this still will give me a carry even though the result will be just 1 can anyone please help me with this?
@AntaroopGhosh
@AntaroopGhosh 2 жыл бұрын
class Solution: def addBinary(self, a: str, b: str) -> str: a1=int(a,2) b1=int(b,2) sum1=a1+b1 return bin(sum1)[2:]
@NN-uy6ik
@NN-uy6ik 2 жыл бұрын
Incredible 😮😮😮😮
@sabrish7263
@sabrish7263 3 жыл бұрын
Why not bin to int -> add 2 ints-> int to bin and return
@NeetCode
@NeetCode 3 жыл бұрын
Yeah, I think that's also a valid solution
@stan8851
@stan8851 3 жыл бұрын
I don't think the interviewer want to see this solution, they want to see how you deal with the edge cases of this problem
@roshni962
@roshni962 3 жыл бұрын
@@NeetCode Wont work for INT_MAX
@aniruddh3423
@aniruddh3423 2 жыл бұрын
idk if this counts as cheating but return str(bin(int(a,2)+int(b,2)))[2:]
@FaizanShaikh-zg9to
@FaizanShaikh-zg9to Жыл бұрын
Hello I hava a doubt can we use inbuild function like bin class Solution: def addBinary(self, a: str, b: str) -> str: return bin(int(a, 2) + int(b, 2))[2:] the code works pretty efficiently but is it the right way?
@xmnemonic
@xmnemonic Жыл бұрын
should be medium
@diptopodder1011
@diptopodder1011 2 жыл бұрын
class Solution: def addBinary(self, a: str, b: str) -> str: s1 = int(a, 2) s2= int(b, 2) s=s1+s2 return bin(s).replace("0b", "")
@meetugupta602
@meetugupta602 2 жыл бұрын
can someone tell my error niothing is shown in the output class Solution { public: string solve(string a , string b){ int countfirst=0; int diff = a.size()-b.size(); // int countsecond=0; string s; int carry=0; for(int i=b.size()-1;countfirst > b.size();i--){ if (a[i + diff] + b[i] + carry == 0){ carry=0; s.push_back(0); } else if (a[i + diff] + b[i] + carry == 1){ carry=0; s.push_back(1); } else if (a[i + diff] + b[i] + carry == 2){ carry = 1; s.push_back(0); } else if (a[i + diff] + b[i] + carry == 3){ carry=1; s.push_back(1); } countfirst++; } for(int i=a.size()-b.size()-1;i>=0;i--){ if (a[i] + carry == 0){ carry=0; s.push_back(0); } else if (a[i] + carry == 1){ carry=0; s.push_back(1); } else if (a[i] + carry == 2){ carry=1; s.push_back(0); } } if (carry == 1){ s.push_back(1); } // reverse(s.begin() , s.end()); return s; } string addBinary(string a, string b) { if (a.size() >= b.size()){ string s = solve(a,b); return s; } string s=solve(b,a); return s; } };
@edwardteach2
@edwardteach2 6 ай бұрын
U a binary God
@akashThe99
@akashThe99 2 жыл бұрын
the second example showing wrong answer with this solution
@shadowfiend8549
@shadowfiend8549 Жыл бұрын
i was not even able to solve this one is this abnormal ?
@dynaspinner64
@dynaspinner64 8 ай бұрын
We all start from somewhere. Once you practice enough easys and re do them you will find them easy.
@Levelord92
@Levelord92 2 жыл бұрын
Come on... this is really an "Easy" task?
@Jaffar87
@Jaffar87 2 жыл бұрын
solve all leetcode problems
@rddcol
@rddcol Жыл бұрын
How is this supposed to be easy 😭😭😭😭😭😭😭. Not understanding shit . Somebody tell me where to start ;
Add Binary - Leetcode 67 - Bit Manipulation (Python)
8:20
Greg Hogg
Рет қаралды 6 М.
Brick Wall - Leetcode 554 - Python
14:40
NeetCode
Рет қаралды 24 М.
If people acted like cats 🙀😹 LeoNata family #shorts
00:22
LeoNata Family
Рет қаралды 30 МЛН
SIZE DOESN’T MATTER @benjaminjiujitsu
00:46
Natan por Aí
Рет қаралды 7 МЛН
Yay😃 Let's make a Cute Handbag for me 👜 #diycrafts #shorts
00:33
LearnToon - Learn & Play
Рет қаралды 117 МЛН
LeetCode 67. Add Binary Solution Explained - Java
10:24
Nick White
Рет қаралды 48 М.
Let's code a beginner Python BANKING PROGRAM 💰
15:01
Bro Code
Рет қаралды 271 М.
Mastering Dynamic Programming - How to solve any interview problem (Part 1)
19:41
Subarray Sum Equals K - Prefix Sums - Leetcode 560 - Python
15:19
Add Binary (LeetCode) | Adding Binary Numbers as Strings Explained
12:43
2 Years of C++ Programming
8:20
Zyger
Рет қаралды 8 М.
Binary Subarrays with Sum - Leetcode 930 - Python
9:57
NeetCodeIO
Рет қаралды 19 М.
Dynamic Programming isn't too hard. You just don't know what it is.
22:31
DecodingIntuition
Рет қаралды 200 М.
5 Simple Steps for Solving Any Recursive Problem
21:03
Reducible
Рет қаралды 1,2 МЛН
Fake Samsung Galaxy S25 Ultra Plus на iOS
0:59
Wylsacom
Рет қаралды 422 М.
Máy báo động cho gia đình mãi đỉnh
0:31
SaboMall
Рет қаралды 34 МЛН
Nokia now vs Then 💀🗿 #blowup #nokia #edit #foryou
0:31
skullmaxx
Рет қаралды 21 МЛН