Add Binary - Leetcode 67 - Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 3 ธ.ค. 2024

ความคิดเห็น • 88

  • @NeetCode
    @NeetCode  3 ปีที่แล้ว +14

    ✏️ Have problem suggestions you would like me to solve? Feel free to comment them below :~)

    • @vijaychikkannavar5060
      @vijaychikkannavar5060 2 ปีที่แล้ว +3

      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

  • @yoshi4980
    @yoshi4980 3 ปีที่แล้ว +31

    an easy problem that can get boggled down in edge cases, really like some the tricks you used. great video as always!

  • @shakhzod_shermatov
    @shakhzod_shermatov หลายเดือนก่อน +1

    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.❤

  • @srinadhp
    @srinadhp 3 ปีที่แล้ว +16

    Love the way you write the code. Concise.
    Love the loop of max of lengths.
    Great explanation as usual

  • @sunnilabeouf
    @sunnilabeouf 3 ปีที่แล้ว +49

    Can't we just use int(a[i]) to cast it to an integer?

    • @NeetCode
      @NeetCode  3 ปีที่แล้ว +29

      Yeah, you're right, I just remembered that. Thanks for pointing it out.

    • @surbhirohilla5139
      @surbhirohilla5139 2 ปีที่แล้ว +5

      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 ปีที่แล้ว +8

      @@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

  • @strawberriesandcream2863
    @strawberriesandcream2863 2 ปีที่แล้ว +3

    thanks, you're a lifesaver when it comes to leetcode

  • @rachnaramkumar
    @rachnaramkumar 2 ปีที่แล้ว +13

    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 ปีที่แล้ว +1

      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 ปีที่แล้ว +15

    Hi at 5:10, couldnt you use int() instead of ord() to cast the char?

  • @akhileshb5859
    @akhileshb5859 2 ปีที่แล้ว +3

    You are a good teacher. Keep up the good work. Thank you!

  • @sanjayp7027
    @sanjayp7027 3 ปีที่แล้ว +40

    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 😅

  • @muzikjay
    @muzikjay 2 ปีที่แล้ว +12

    "Let's go back to elementary school and add these together. What happens when we add 1 and 1?.....0?" 😂

  • @beldam94
    @beldam94 2 ปีที่แล้ว +3

    This code is simply beautiful. Thanks.

  • @vikasz2
    @vikasz2 ปีที่แล้ว +2

    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

  • @karthikkumaresan1091
    @karthikkumaresan1091 3 ปีที่แล้ว +3

    What is the time complexity of the string concats in python(eg. char + res in the example above)

  • @sriramkarthikakella2033
    @sriramkarthikakella2033 ปีที่แล้ว +3

    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

  • @BurhanAijaz
    @BurhanAijaz ปีที่แล้ว +2

    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

  • @sagargulati639
    @sagargulati639 2 ปีที่แล้ว +4

    The returned res should be reversed to get the original output.
    return res[::-1]

  • @clara8490
    @clara8490 3 ปีที่แล้ว +4

    Amazing video and nice explanation!!!

  • @cedriczhang6129
    @cedriczhang6129 16 วันที่ผ่านมา

    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:]

  • @RohanVenkateshGupta
    @RohanVenkateshGupta 2 ปีที่แล้ว +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

  • @MaxFung
    @MaxFung ปีที่แล้ว

    Youre an amazing teacher mr. neet!

  • @torontonian77
    @torontonian77 2 ปีที่แล้ว +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

  • @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.

  • @XzcutioneR2
    @XzcutioneR2 ปีที่แล้ว +3

    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

  • @triplestrikee875
    @triplestrikee875 3 ปีที่แล้ว +4

    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

  • @andrewromanenkov6929
    @andrewromanenkov6929 3 ปีที่แล้ว +4

    Answer in 2 lines of code:
    c = bin(int(a,2) + int(b,2))
    return c[2:]

    • @willd9807
      @willd9807 2 ปีที่แล้ว +2

      print(eval())

    • @ohyash
      @ohyash 2 ปีที่แล้ว +1

      Interviewer: _Pikachu face_

    • @Levelord92
      @Levelord92 2 ปีที่แล้ว

      yeah, put 9223372036854775807 and 9223372036854775807 as summands and see what happens, genius

  • @geraldakorli
    @geraldakorli 11 หลายเดือนก่อน

    Why didn't you use int function on the values a[i] and b[i]?

  • @malh851
    @malh851 ปีที่แล้ว

    Great Explanation!
    Might be cleaner to use the divmod() function instead of % and //.
    Eg.
    char, carry = divmod(total, 2)
    res = str(char) + res

  • @jankeshchakravarthy9389
    @jankeshchakravarthy9389 ปีที่แล้ว

    Nice explanation. Did you forget to reverse the result??

  • @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!

  • @ShivangiSingh-wc3gk
    @ShivangiSingh-wc3gk 2 หลายเดือนก่อน

    I was thinking that the interviewer would want the bit manipulation solution for this

  • @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;
    };

  • @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 :(

  • @abisheknair3545
    @abisheknair3545 2 ปีที่แล้ว

    int(a[i]) worked succesfully. so why did u use ord?

  • @duncanproctor7160
    @duncanproctor7160 2 ปีที่แล้ว +1

    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.

  • @Salah-YT
    @Salah-YT 2 ปีที่แล้ว +1

    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

  • @xmnemonic
    @xmnemonic ปีที่แล้ว +1

    should be medium

  • @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

  • @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?

  • @sabrish7263
    @sabrish7263 3 ปีที่แล้ว

    Why not bin to int -> add 2 ints-> int to bin and return

    • @NeetCode
      @NeetCode  3 ปีที่แล้ว +1

      Yeah, I think that's also a valid solution

    • @stan8851
      @stan8851 3 ปีที่แล้ว +1

      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 ปีที่แล้ว +3

      @@NeetCode Wont work for INT_MAX

  • @mehmetnadi8930
    @mehmetnadi8930 2 ปีที่แล้ว +3

    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 ปีที่แล้ว +4

      Absolutely, I struggled a lot with easy questions when I started. Eventually you will make progress!

    • @pcccmn
      @pcccmn 2 ปีที่แล้ว +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 ปีที่แล้ว +1

      @@pcccmn how is it going? Did you improve?

  • @edwardteach2
    @edwardteach2 6 หลายเดือนก่อน

    U a binary God

  • @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?

  • @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;
    }
    };

  • @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", "")

  • @AntaroopGhosh
    @AntaroopGhosh 2 ปีที่แล้ว +1

    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 😮😮😮😮

  • @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 9 หลายเดือนก่อน

      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
    ;