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
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.❤
@@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
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?
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.
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
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:]
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
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.
@@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
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.
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
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
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?
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.
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?
✏️ Have problem suggestions you would like me to solve? Feel free to comment them below :~)
last line should be return res[::-1] to reverse it back to original format
@@vijaychikkannavar5060 Yes you are right.
@@vijaychikkannavar5060 no
Diagonal Matrix problem
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
an easy problem that can get boggled down in edge cases, really like some the tricks you used. great video as always!
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.❤
Love the way you write the code. Concise.
Love the loop of max of lengths.
Great explanation as usual
Can't we just use int(a[i]) to cast it to an integer?
Yeah, you're right, I just remembered that. Thanks for pointing it out.
I was thinking the same and thougth what's the meaning of ord(0) which I can't understand😂lol, it was a mistake
@@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
thanks, you're a lifesaver when it comes to leetcode
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?
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.
Hi at 5:10, couldnt you use int() instead of ord() to cast the char?
Yes. you can.
You are a good teacher. Keep up the good work. Thank you!
how is this a easy problem :|
It's an easy but long problem for me. I solved it my way without any math 😅
"Let's go back to elementary school and add these together. What happens when we add 1 and 1?.....0?" 😂
this...
This code is simply beautiful. Thanks.
def addBinary(self, a: str, b: str) -> str:
a = int(a,2)
b = int(b,2)
res = a+b
return bin(res)[2:]
Bro can you explain to me this code please
What is the time complexity of the string concats in python(eg. char + res in the example above)
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")?
that worked for me in my solution
we can use the same code for the question : leetcode 413(Add strings),just replace 2 by 10
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
The returned res should be reversed to get the original output.
return res[::-1]
nah see how is appending
Amazing video and nice explanation!!!
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:]
Wonderful Explanation 👍👍👍
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
Youre an amazing teacher mr. neet!
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
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.
Why not just do bin(int(a, 2) + int(b, 2))[2:] ?
There is no time complexity and space complexity mentioned in the problem. This should be fine i guess
Very well explained, but don't we need to return res[::-1]?
Never mind, I thought res = char + res in the loop is same as res += char. My bad.
@@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
Answer in 2 lines of code:
c = bin(int(a,2) + int(b,2))
return c[2:]
print(eval())
Interviewer: _Pikachu face_
yeah, put 9223372036854775807 and 9223372036854775807 as summands and see what happens, genius
Why didn't you use int function on the values a[i] and b[i]?
Great Explanation!
Might be cleaner to use the divmod() function instead of % and //.
Eg.
char, carry = divmod(total, 2)
res = str(char) + res
Nice explanation. Did you forget to reverse the result??
Why are we usig "ord" instead of "int(str)" ?? @NeetCode
Thank you for explaining what happens when you add "11" and "11". I was completely lost but not anymore thanks to you!
I was thinking that the interviewer would want the bit manipulation solution for this
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;
};
I havent run the code, but did you get a character short each time from your reversing method.
a,b = reversed(a), reversed(b)
I implemented same approach for Dart, it gave Time Limit Exceeded, but for java it worked :(
int(a[i]) worked succesfully. so why did u use ord?
Why not just pad the shorter string with leading zeros?
interesting...
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.
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
should be medium
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
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?
Why not bin to int -> add 2 ints-> int to bin and return
Yeah, I think that's also a valid solution
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
@@NeetCode Wont work for INT_MAX
is it normal to find "easy" questions hard? i mean i don't think most of the easy question are actually easy ngl :///
Absolutely, I struggled a lot with easy questions when I started. Eventually you will make progress!
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.
@@pcccmn how is it going? Did you improve?
U a binary God
idk if this counts as cheating but
return str(bin(int(a,2)+int(b,2)))[2:]
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?
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;
}
};
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", "")
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:]
Incredible 😮😮😮😮
the second example showing wrong answer with this solution
i was not even able to solve this one is this abnormal ?
We all start from somewhere. Once you practice enough easys and re do them you will find them easy.
Come on... this is really an "Easy" task?
solve all leetcode problems
How is this supposed to be easy 😭😭😭😭😭😭😭. Not understanding shit . Somebody tell me where to start
;