Add Two Numbers - Leetcode 2 - Python

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

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

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

    🚀 neetcode.io/ - A better way to prepare for Coding Interviews

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

      Seems like the code is not working. Showed me the wrong result when compile.

  • @e-raticartist
    @e-raticartist ปีที่แล้ว +493

    hearing "hey guys i'm still unemployed so let's solve a leetcode problem today" and knowing you became a software engineer at google is so real and inspiring bro, thanks

    • @alwin5995
      @alwin5995 9 หลายเดือนก่อน +31

      Bruh he left job at amazon, and decided to voluntarily be unemployed. Dude's been a genius all along.

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

    "hey guys i am still unemployed so lets solve a problem " this is savage bro

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

    that intro hit me different

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

    I get so inspired/motivated when you mention unemployment in your old videos because of where you ended up

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

    "hey guys i am still unemployed so lets solve a problem " this one cracked me up because right now all your efforts paid off and look back, we all have been there..ah what a journey!!!

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

    I've been watching your solutions for a while now and I'm just so happy that I finally started to solve problems like the way you do. Thank you so much!!

  • @oooo-rc2yf
    @oooo-rc2yf 3 ปีที่แล้ว +10

    If the person teaching these is unemployed what chances do we have...

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

    That beginning took me by surprise, instantly made my evening better. Thanks

  • @Eftahhh
    @Eftahhh 4 ปีที่แล้ว +96

    So simple, thank you. I was casting the linked list values to strings and reversing them, then casting them back to ints and adding them... needless to say I was making spaghetti.
    Your example is very clean!

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

      lol that was my initial solution as well! got dirty real quick

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

      I did same, thanks

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

      @@prudvi01 I used an if statement inside a while loop, would that be wrong even if it works, if not what's wrong with it ? As in does the solution have to be a linked list.

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

      I did the same. I'm not convinved it's any worse than the solution presented in the video. looping through two linked lists (and a third for the output) is O(n) time complexity.

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

      def addTwoNumbers(l1,l2):
      l1.reverse()
      l2.reverse()
      l1s= str(l1)
      l2s= str(l2)
      l1s= "".join(l1s)
      l2s= "".join(l2s)
      l1 = ""
      l2 = ""
      for i in range(1, len(l1s), 3):
      l1 +=l1s[i]
      for i in range(1, len(l2s), 3):
      l2 +=l2s[i]
      l1s=int(l1)
      l2s=int(l2)
      res=l1s+l2s
      res= str(res)
      res= list(res)
      res.reverse()
      return res

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

    Excellent! Clear and plain explanations, and it's so much cleaner when hand mark-up is by pen instead of by mouse. :)
    This is linked in LeetCode as "optimized solution explained" on the problem itself, but it'd be faster to take:
    carry = val // 10
    val = val % 10
    ...and make it instead:
    carry = 1
    val = val - 10
    The modulus approach is fantastic for expanding our algorithm to support adding up three or more arrays, but in our use case carry will always be 0 or 1.

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

      You would require 'if' statements.
      if val >= 10:
      carry = 1
      val = val - 10
      Which would reduce the elegance of code

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

      Nothing about this problem is elegant or worth optimization.

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

    I traversed through both linked list and got the actual numbers, added them, then created a linked list with the result's digits as nodes.

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

      hi, Please let me know. Why is the value divided by 10? I'm learning how to code and I don't know where he got the number 10? (on minute 7:29)

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

      ​@@inspisiavideos8542 You divide by 10 so that you can add it to the next number which will be in the next 10's place. For example: if you took 25 + 26 if you add 5 + 6 and then divide by 10 you'll get 1. So i take my one and add it to the next 10's place which is 2 + 2 + 1 that i got from carrying the number which will total 51.

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

      @@danielwilczak7833 Thank you so much!!! I got an internship during this Summer as QA and just finished it but I asked for an extension and if I could get it this time as Dev. They said yes. I have coded before with courses on how to make websites but I have never done code questions. Basically this next week is my first week. It’s so hard to get a job so they told me that they don’t have entry level positions and senior positions are more than likely ending up on people who are already in the company. So basically I’m learning as much as I can during my spare time to then perhaps they let me stay after the internship extension ends by the end of the year.

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

      @@inspisiavideos8542 Congrats on your internship! Calling out 10 as a "magic number" is really great - bare numbers with no evident explanation can cause a lot of confusion in code, so 10 could be a constant called NUMBER_BASE since we're just using decimal notation here. For extra fun, make it not a constant, and adapt the algorithm to work in number bases other than 10!

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

      @@philhamlin7935 hey thanks! My internship was supposed to end in August but was extended to the end of December. I’ve been applying to other companies but nothing yet even though I have projects on my portfolio. My internship manager told me to stay alert when an opening occurs and apply. 2 positions opened and I applied there this week. Hopefully they’ll let me know and I be ready for a test code. The company has many teams so probably the person who sees my resume doesn’t know me yet.

  • @vinaykumar-gg4mx
    @vinaykumar-gg4mx 2 ปีที่แล้ว +3

    A complete beginner question, how to call and declare the inputs for addTwoNumbers function,
    just to test the program !

  • @shooby117
    @shooby117 9 หลายเดือนก่อน +2

    "hey guys i am still unemployed so lets solve a problem" mans representing his entire audience 😂😂😂

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

    This code only passes 1365/1568 test cases. Update needed.

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

    Congratulations that you are now employed!! Happy for you!

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

    @NeetCode Could you please explain the time complexity of the problems you solve? It will be really useful for us.

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

      For this one it should be O(n + m), where n is length of first linked list and m is length of second linked list.

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

      @@wlockuz4467 no bro... Either O(n) or O(n+1) where n is the length of linked list which has more nodes

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

      Can you please explain what will be the time complexity and space complexity for this piece of code in example?

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

      @@alok7485 Time complexity will be O(max(n, m)) and Space complexity will be O(max(m,n))

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

    Hopefully you found a job!

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

    Dude, thankyou for this solutions. They are helping me alottttt! Also, if you could please make a video on intersection of two linked lists

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

      Can you please explain what will be the time complexity and space complexity for this piece of code in example?

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

    Why are these things so difficult 😣?

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

    Can someone explain why we don't use the first dummy list node? Why not use dummy.val and assign?

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

      I think it's because we want the logic to be "the next thing is ___" for every iteration, so we make a dummy list node and immediately start with our logic (the next thing for the dummy node is ___). If you use dummy.val, you have the first step do the logic of "the value here is ___" and then the later steps are "the next thing is ___" which is more inconvenient to write.
      That's how I thought of it, not sure if that's the right way to think about it.

  • @hwang1607
    @hwang1607 10 หลายเดือนก่อน

    is it bad to convert them to ints and add them then make a new linked list? 💀
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
    n1 = ""
    n2 = ""
    while l1:
    n1 += str(l1.val)
    l1 = l1.next
    while l2:
    n2 += str(l2.val)
    l2 = l2.next
    total = int(n1[::-1]) + int(n2[::-1])
    total = str(total)[::-1]
    res = dummy = ListNode()
    for n in total:
    new = ListNode(n)
    dummy.next = new
    dummy = dummy.next
    return res.next

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

    Here after when you got job in Google.... congratulations:)

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

    Better explanation than the official solution explanation.

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

    nulll and zero are different, you should instead append the while statement to while l1 or l2 or carry>0

    • @jaspreetsahota1840
      @jaspreetsahota1840 9 หลายเดือนก่อน

      In python, 0 evaluates to its Boolean value (False) in a conditional clause. So it's fine to just have carry.

    • @TheEllod
      @TheEllod 9 หลายเดือนก่อน

      @jaspreetsahota1840 good to know!

  • @EranM
    @EranM 4 หลายเดือนก่อน

    "Hey guys, I'm still unemployed.." Many kisses for you neet! you make me laugh.. And relax... To the best ASMR Channel OUT-THERE!!!! Please go back to this microphone and keyboard, and relaxed voice!!!!!!!!! damn I enjoy this

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

    I have interview on 21st March, there is no way I am gonna pass :(
    This level of programming is going above my head

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

    i solved it using more memory but it eliminates thinking about edge cases:
    nums1, nums2 = [], []
    cur = l1
    while cur:
    nums1.append(cur.val)
    cur = cur.next
    cur = l2
    while cur:
    nums2.append(cur.val)
    cur = cur.next

    nums1 = nums1[::-1]
    nums2 = nums2[::-1]

    num1 = int(''.join(map(str, nums1)))
    num2 = int(''.join(map(str, nums2)))
    vals = []
    number = str(num1 + num2)
    for c in number:
    vals.append(int(c))
    dummy = ListNode(0)
    cur = dummy
    while vals:
    cur.next = ListNode(vals.pop())
    cur = cur.next

    return dummy.next

  • @IvanRadonjic-j9f
    @IvanRadonjic-j9f 8 หลายเดือนก่อน

    # Definition for singly-linked list.
    # class ListNode(object):
    # def __init__(self, val=0, next=None):
    # self.val = val
    # self.next = next
    class Solution(object):
    def addTwoNumbers(self, l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """
    def reverse_in_place(head):
    before = None
    temp = head
    while temp is not None:
    after = temp.next
    temp.next = before #flip pointer
    before = temp #cross 'gap'
    temp = after # move temp over
    return before #before is the new head of reversed LL
    l1 = reverse_in_place(l1)
    l2 = reverse_in_place(l2)
    temp_l1 = l1
    l1_val = ""
    temp_l2 = l2
    l2_val = ""
    while temp_l1 is not None:
    l1_val += str(temp_l1.val)
    temp_l1 = temp_l1.next
    while temp_l2 is not None:
    l2_val += str(temp_l2.val)
    temp_l2 = temp_l2.next
    total = int(l1_val) + int(l2_val)
    total = str(total)
    temp_out = ListNode(int(total[0]))
    new_LL = temp_out
    for i in range(1, len(total)):
    if temp_out.next is None:
    temp_out.next = ListNode(int(total[i]))
    temp_out = temp_out.next
    new_LL = reverse_in_place(new_LL)
    return new_LL
    This is my brute force method for this problem but i dont think its THAT bad on time and space complexity LOL what do you guys thing

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

    By far the best explanation of this problem I’ve seen 👏 Thanks for sharing

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

    Are you still unemployed?

  • @stylisgames
    @stylisgames 3 หลายเดือนก่อน

    I was able to solve this one, but did not think of dividing the current sum by 10 and using Math.floor() to get the first digit as the carry number, and then using modulo to get the second number aka the current sum. So darn clever! Instead I converted the sum to a string and grabbed the values by index.

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

    I cant figure out how does cur work. If I print id(cur) == id(dummy) it's true, but if i print cur and dummy inside or after while cycle the output is different. Tell me please what's going on or What should I google to clarify that ?

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

    A little confused,how are we adding in reverse order?
    we're just adding v1 and v2 which is normal addition isn't it?

  • @michaelwilliams8986
    @michaelwilliams8986 7 วันที่ผ่านมา

    I'm getting memory limit exceeded. Did something change on Leetcode's end?

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

    what's the function of next and val do?

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

    I got some errors when I ran your exact code. Is your solution missing the case when the highest position creates a carry of 1?

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

      you might have missed the "+ carry" bit when summing up the "val"

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

      while l1 or l1 or carry:

  • @NeilSharma-u5n
    @NeilSharma-u5n 29 วันที่ผ่านมา

    The first medium LL problem I could solve with optimized code.

  • @tomonkysinatree
    @tomonkysinatree 3 หลายเดือนก่อน

    I was really close to the solution on this one. I had an extra node at the end because I was creating my node in cur instead of cur.next(). Slowly getting better at these

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

    I did 'print(Solution().addTwoNumbers(l1,l2))' and got error "list object has no attribute 'val'... how do I fix it?

  • @Moon-li9ki
    @Moon-li9ki 4 หลายเดือนก่อน

    I'm really proud of mylsef. I finally managed to solve a medium problem by myself, although my solution was slow as hell xd

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

    To deal with edge case just before . return dummy.next write
    If carry==1: cur.next= ListNode (1)

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

    can someone please explain why dummy.next gives the full listnode in return? ( if i go dummy.next.val it gives y the value of the second node)

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

      We are treating dummy.next as the head node. Dummy.next.val contains the value of the head node, and dummy.next.next contains the next node and so on. Basically we created the dummy node to avoid setting head node = firstvalue and then doing head.next for the others

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

      Thank you

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

    Can Some please explain why the dummy is still getting updated when after the first iteration cur is updated to a different object. newNode = ListNode(columnSum % 10)
    curr.next = newNode
    curr = newNode

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

      At the start of the loop cur = dummy. On the first iteration you are assigning cur.next (aka dummy.next) with the first digit of the solution. So now dummy.next equals the head node of the solution so at the end we return dummy.next. dummy.next will always point to this head node no matter what cur gets changed to.

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

      Hi Sajith, Here a good explanation: stackoverflow.com/questions/58759348/when-does-a-pointer-to-a-linked-list-change-the-actual-list

    • @drainedzombie2508
      @drainedzombie2508 8 หลายเดือนก่อน

      @@ai4sme Thanks for this. TIL python variables are essentially references/pointers to objects i.e. class instances.

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

    You are best. I always pause ads blocker for you.

  • @passionatechristianworker
    @passionatechristianworker 5 หลายเดือนก่อน

    "you probably do but you might think you don't".
    Haha, thanks for the encouragement.

  • @TobiasLange-n5c
    @TobiasLange-n5c หลายเดือนก่อน

    Why do you write in the while loop just "l1 or l2 or carry"

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

    Awesome, I love how you dealt with all the edge cases without cluttering the code

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

    Did you find a job now?

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

    could have reduced these statements within single block, otherwise awesome explanation thank you
    if(l1 != null){
    v1 = l1.val;
    l1 = l1.next;
    }

    if(l2 != null){
    v2 = l2.val;
    l2 = l2.next;
    }

  • @thebaddest-v9w
    @thebaddest-v9w 5 หลายเดือนก่อน

    Why my code is not working can any one correct this code.
    /**
    * Definition for singly-linked list.
    * public class ListNode {
    * int val;
    * ListNode next;
    * ListNode() {}
    * ListNode(int val) { this.val = val; }
    * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    * }
    */
    class Solution {
    public ListNode head = null;
    public ListNode tail = null;
    public void addNode(int data) {
    ListNode newNode = new ListNode(data);
    if(head == null) {
    head = newNode;
    tail = newNode;
    }
    else {
    tail.next = newNode;
    tail = newNode;
    }
    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    int num1=0;
    int num2=0;
    int a;
    int i=1;
    ListNode temp1 = l1;
    ListNode temp2 = l2;
    while(temp1 != null && temp2 !=null){
    //coverting this to number
    num1 = num1+((temp1.val)*i);
    num2 = num2+((temp2.val)*i);
    i=i*10;
    temp1 = temp1.next;
    temp2 = temp2.next;
    }
    System.out.println(num1+" "+num2);
    // adding two numbers
    int num3 = num1+num2;
    while(num3>0){
    //insert the nodes
    a = num3%10;
    if(a==0)
    addNode(0);
    else
    addNode(a);
    // here the zero is not inserting
    num3 = num3/10;
    }
    return head;
    }
    }

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

    Wow this is so clean✅✅
    I brute- forced my way to this problem and it's functional but really ugly 😀

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

    NC: You do probably remember how to add two numbers together
    Me: You severely overestimate my abilities

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

    I don't understand what's going on with carry. Wouldn't always be a left over number there by the time two get to the second digit in the list nodes.
    First time through: val = 2 + 5 + 0
    carry = 7 // 10
    Doesn't that leave carry as .7 when we get to the next digits? I'm very confused.

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

      In Python, we can perform floor division (also sometimes known as integer division) using the // operator. This operator will divide the first argument by the second and round the result down to the nearest whole number
      So, 7 // 10 = 0

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

    its interesting how you build the answer after the dummy node and return the answer. Its not like the test cases can detect the dummy node

  • @SweVillian-mt6nk
    @SweVillian-mt6nk 7 หลายเดือนก่อน

    This intro make this video my favorite one 😂. Could be a useful cue to remember the solution in an interview even.

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

    Can anybody explain me? In the begin we wrote "dummy = cur". After that we updating "cur" in the while-loop. But we don't update "dummy". So how "dummy" is updating together with "cur" if we don't redefine "dummy = ..."

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

      Exactly my doubt!!!

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

    For some reason it was extremely easy problem for me, first time that I just saw the solution instantly in full (unlike all “easy” ones before) and was so surprised of everyone’s animosity to this problem, lol.

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

    Can you explain how can I call the l1 and l2 listnodes in the addtwonumber function to test?

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

      it's a bit compicated to explain it in words. I would rather suggest you to watch the videos on how to create linklist object and other related problems ( which aren't directly given into the function like this leetcode problem)

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

      @@crosswalker45 hi, thanks a lot man.

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

    Couldn’t have solved this without you. Thank you so much

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

      Can you please explain what will be the time complexity and space complexity for this piece of code in example?

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

    Bruh, my dumb ass thought transforming the f*cking linked list into a number and than adding both together and making another linked list of that was easier
    "Error - found cycle" disagree...

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

      That also works!
      I solved it like that first. But this is a better approach lol. Removes the pain of converting linked list to integer and then back to linked list.

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

    Can someone explain the dummy listnode and how changing in cur changes dummy?

  • @serpent2776
    @serpent2776 4 หลายเดือนก่อน

    I am so happy that LC decided to give us reversed lists for this problem

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

    The Leetcode dislike count was a useful metric

  • @DanielSmith-uj7rr
    @DanielSmith-uj7rr 2 ปีที่แล้ว

    BRO! UNIQUE..!! "Hey Guys, I am still UNEMPLOYED so let's solve a problem!" Lmao!😂

  • @nivethanyogarajah1493
    @nivethanyogarajah1493 วันที่ผ่านมา

    Legendary Introduction!

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

    Why can't you reverse both list and just add the two reversed list together?

  • @anamikaborah5393
    @anamikaborah5393 7 หลายเดือนก่อน

    Love how you started the video! xD You made my life easier by posting these videos. Great work! :) :D

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

    i hate the problem already simply because i didn't understand the solution

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

    doesn't dummy.next return the head of the list?

  • @02devavratkumarmahato11
    @02devavratkumarmahato11 2 หลายเดือนก่อน +1

    Why can't we just return cur.next ??

    • @02devavratkumarmahato11
      @02devavratkumarmahato11 2 หลายเดือนก่อน

      I mean the cur is pointing to dummy right? So just print it right idk if I'm right

    • @AdityaRaut-l6p
      @AdityaRaut-l6p หลายเดือนก่อน

      i think that will skip first value

  • @MatthewPostrel
    @MatthewPostrel 10 หลายเดือนก่อน

    Explanation was crystal clear and helped me solve the problem super quick. Thanks!

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

    Why can;t we simply reverse two lists first, sum them and then reverse an output?

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

    Thanks for making this. Trying this problem is the first time I've ever tried using a Linked List, so this helped solidify the solution LeetCode provides.

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

      Can you please explain what will be the time complexity and space complexity for this piece of code in example?

  • @JC-yo5hu
    @JC-yo5hu ปีที่แล้ว

    When was dummy head ever updated in the code? Please help!

  • @MrYosuko
    @MrYosuko 8 หลายเดือนก่อน

    The intro slapped me back into reality. As always, thanks for the awesome explanations 😄

  • @Silver-lu1dt
    @Silver-lu1dt 8 หลายเดือนก่อน

    This is the way I learnt about pointer, I can't believe it

  • @passionatechristianworker
    @passionatechristianworker 5 หลายเดือนก่อน

    i'm amazed at your ability. it's the nuances in the code that's the hardest to figure out. kudos to you.

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

    Wow, this was very well explained!

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

    Hi. Can someone help me understand how and why there is l1.val?
    I thought l1 is a list which is [2, 4, 3]? How does l1.val calling integer 2?
    Or it's from ListNode class? I'm very confused.

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

      if you see the ListNode class there is a val, which is used to access the int values of the nodes so it is used as node.val (in this case l1.val) hope it helps

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

      Hi @@smilenpassion thank you for your respond, but I am still confused.
      Class listnode is not inheritance under class solution. How can class solution call any object from class listnode?
      Also, even it can call the object from listnode, shouldn't be v1 = self.val if l1? Or set the self.val to l1.val?
      Thank you again for helping me to understand it

  • @rohanmahajan6333
    @rohanmahajan6333 8 หลายเดือนก่อน

    so do we have a first node that is just null in all of these

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

    Man I was super stressed out solving these leetcodes, but the " Hey I am still unemployed" made my day! LMAO

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

    Stupid question but how does "dummy" get updated when all code changes are done to "cur"?

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

      Both dummy and cur are both pointers to the same list, but serve different purposes: We are using dummy to point to the start of the list and cur will be used to add additional nodes + move to the latest node in the list.

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

    Can someone explain what happens inside the stack with the statements "cur = dummy" and "return dummy.next"?

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

      curr is what you use to traverse the dummy linked list, while, "dummy" will always point at the head of the linked list. Since you're returning "dummy.next" you'll be returning the head of the resultant linked list.

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

    0:00 Lol now you're at Google. Here I am just trying to get Amazon or Microsoft now.
    Awesome solution, I managed to actually solve this one myself but wanted to see your way of doing it, much cleaner. Thank you! Liked!

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

    Only Platform I choose for any coding explanation

  • @tirasjeffrey2002
    @tirasjeffrey2002 10 หลายเดือนก่อน

    can anyone tell me why we're returning the dummy.next and not dummy itself? wont we be able to access every other element if we just return dummy?

    • @tsunningwah3471
      @tsunningwah3471 9 หลายเดือนก่อน

      yes i have the same question too. I thought dummy itself is the real list

    • @m0sh3
      @m0sh3 9 หลายเดือนก่อน

      @@tsunningwah3471 dummy is initialized to default value of 0 for the purpose of having an initial node to attach everything else to. dummy.next is the real start of the summed list.

    • @tsunningwah3471
      @tsunningwah3471 9 หลายเดือนก่อน

      @@m0sh3 thanks got it!

  • @mesbahkingpro
    @mesbahkingpro 7 หลายเดือนก่อน

    who the he are you
    🕵🕵🕵🕵🕵🕵

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

    Great video and great channel I am very excited to discover this channel I hope I benefit from this channel a lot .Thanks a lot😊

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

    Haha, now you are so employed! Thanks for these great contents!

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

    At the start of the loop cur = dummy. On the first iteration you are assigning cur.next (aka dummy.next) with the first digit of the solution. So now dummy.next equals the head node of the solution so at the end we return dummy.next. dummy.next will always point to this head node no matter what cur gets changed to.

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

      I quote your response to ask the question further. As I understand, cur = dummy means let cur be dummy, but they are not the same one. I still don't understand whey cur.next will change dummy.next. Did I miss anything? Thank you so much!

    • @oliverbao4925
      @oliverbao4925 9 หลายเดือนก่อน

      @@alicia8170 hi yeah i'm wondering the same thing - although we didn't reference dummy at all or change its value, it gets built on as we change cur and cur.next - is this a python binding or pointer issue?

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

    this solution gives TLE (Time Limit Exceeded) any other solution?

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

      Most likely you have an infinite loop somewhere, are you updating your pointers?

  • @lily_h-m7j
    @lily_h-m7j 2 ปีที่แล้ว +2

    This was hard argh I had no idea how to implement carry. Thank you for explaining! I don't understand the dummy node part. can we not use a dummy node? Why not use curr and return curr?

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

      You could, but in my experience the dummy node generally makes building the linked list easier since you can loop through it with less conditional statements.
      If you don't make the dummy node, you would either have to have a separate if statement to check that our starting node is not null or find some other way to do a one-off initialization of the list. With the dummy node, you can process the nodes each time without having to worry about if it's your starting node or not.

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

    "I am still unemployed" Not anymore!

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

    I hope that you are employed now bro

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

    I am very happy for you that you are employed at Google now. 😀

  • @dr.merlot1532
    @dr.merlot1532 2 ปีที่แล้ว +1

    #Here is the full code to run on your personal machine:
    #Add two numbers:
    class LinkedList:
    def __init__(self):
    self.head = None
    class ListNode:
    def __init__(self,val=0,next=None):
    self.val=val
    self.next=next
    def addTwoNumbers(l1,l2):
    dummy=ListNode()
    cur=dummy
    carry=0
    while l1 or l2 or carry:
    v1=l1.val if l1 else 0
    v2=l2.val if l2 else 0
    #newdigit
    val=v1+v2+carry
    carry=val//10
    val=val%10
    cur.next=ListNode(val)
    cur=cur.next
    l1=l1.next if l1 else None
    l2=l2.next if l2 else None
    return dummy.next
    first_node = ListNode(2)
    second_node = ListNode(4)
    third_node = ListNode(3)
    l1 = LinkedList()
    l1.head = first_node
    first_node.next = second_node
    second_node.next = third_node
    first_nodeb = ListNode(5)
    second_nodeb = ListNode(6)
    third_nodeb = ListNode(4)
    l2 = LinkedList()
    l2.head = first_nodeb
    first_nodeb.next = second_nodeb
    second_nodeb.next = third_nodeb
    string_repr = ""
    node = l1.head
    while node is not None:
    # string_repr += node.val
    # string_repr += " -> "
    string_repr += str(node.val)
    string_repr += " -> "
    node = node.next
    string_repr += "None"
    print(string_repr)
    string_repr = ""
    node = l2.head
    while node is not None:
    # string_repr += node.val
    # string_repr += " -> "
    string_repr += str(node.val)
    string_repr += " -> "
    node = node.next
    string_repr += "None"
    print(string_repr)
    lresult=addTwoNumbers(l1.head,l2.head)
    string_repr = ""
    node = lresult
    while node is not None:
    # string_repr += node.val
    # string_repr += " -> "
    string_repr += str(node.val)
    string_repr += " -> "
    node = node.next
    string_repr += "None"
    print(string_repr)

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

    LOVE you my GURU your awesome!!!

  • @shantipriya370
    @shantipriya370 4 หลายเดือนก่อน

    wonderful explanation

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

    im still unemployed :(