LeetCode Add Two Numbers Solution Explained - Java

แชร์
ฝัง
  • เผยแพร่เมื่อ 1 ต.ค. 2024
  • The Best Place To Learn Anything Coding Related - bit.ly/3MFZLIZ
    Join my free exclusive community built to empower programmers! - www.skool.com/...
    Preparing For Your Coding Interviews? Use These Resources
    --------------------
    (My Course) Data Structures & Algorithms for Coding Interviews - thedailybyte.d...
    AlgoCademy - algocademy.com...
    Daily Coding Interview Questions - bit.ly/3xw1Sqz
    10% Off Of The Best Web Hosting! - hostinger.com/...
    Follow Me on X/Twitter - x.com/nickwhit...
    Follow My Instagram - / nickwwhite
    Other Social Media
    ----------------------------------------------
    Discord - / discord
    Twitch - / nickwhitettv
    TikTok - / nickwhitetiktok
    LinkedIn - / nicholas-w-white
    Show Support
    ------------------------------------------------------------------------------
    Patreon - / nick_white
    PayPal - paypal.me/nick....
    Become A Member - / @nickwhite
    #coding #programming #softwareengineering

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

  • @ManishSingh-dj4yu
    @ManishSingh-dj4yu 4 ปีที่แล้ว +103

    Great.. one suggestion though. Please move your picture position to down left.

    • @0anant0
      @0anant0 4 ปีที่แล้ว +1

      Already done in his newer videos, plus background is transparent.

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

    You do not even try to have a different solution other than the posted solution in LeetCode for the question.
    Its line by line same; even structure is same. What differs here is just name of the variables .. lol
    I am noticing this for a lot of questions from you and believe me sometime you do not even try to explain why something is done in a tricky situation. Just the rote solution from leetcode.
    Please come up with different solutions other than what leetcode already provides.
    I am pretty sure in an interview setup typing almost the same solution as leetcode/algoExpert etc will cause issues as interviewers know and practice that question by looking at those solutions.
    I am not here to judge you my friend but to suggest you that even if you refer those posted solution, when you code, go with your own coding flow and style. Do not come up with memorized posted solutions.

    • @ICeyCeR3Al
      @ICeyCeR3Al 4 ปีที่แล้ว

      this solution is like the absolute best case scenario lol. It takes like a few minutes alone to even understand the scope of the output here. I completed a solution (100 lines of code LOL), but even after all that i forgot what if the sum of the last digits need a carry. I strongly doubt anyone aside from a CS prof or someone who deals with highly logical work (number theorist/mathematicians/Data scientists etc) can pull this off as fast as Nick did lol. Taking Data right now and this problem is equivalent to a weekly practice problem. A whole week. Took me 2 days to finish this particularly one...no where near 6 min.
      Lol wish could of taken a hint from this but my prof doubles down on weekly programs and she would cut 3/4 points off if its not your logic.

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

      Just try to learn and move on lol! Thank him at the very least. He helped a lot of people here

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

    the numbers are bit confusing here because 243+564 = 807 and if you reverse the numbers 342+465 = 807

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

      You do the addition backwards, instead of going right to left, go left to right when adding.

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

      true, first time i looked at that example i thought i missed something

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

    i get almost all of it, i can see how its added and carried over, i just dont understand which part revereses the linked node so that it can be added the way it is added

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

    ListNode dummy_head = new ListNode(0);
    what does the (0) mean, why we have it there?

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

      It has a value of 0, its basically a neat trick you can do so you won't get a pointer error.

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

    I dont get it. When we never assigned any next Node to dummy_head. How did dummy_head still print the right answer?

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

      I do not get that as well. I was going to ask the same thing.

    • @curiousredpand90
      @curiousredpand90 2 หลายเดือนก่อน +3

      because all this time, l3 is modifying for dummy_head. When we point l3 to dummy_head and modify l3, we are also modifying dummy_head. Since we need l3 as a pointer to move around, we need dummy_head to stay at the head of the node to be returned.

  • @NavedKhan-je7el
    @NavedKhan-je7el 4 ปีที่แล้ว +7

    Hey Nick, Thanks for the explanation. It would be a great help if you provide the solution of problem 445 i.e Add two numbers II.

  • @HiBMlive
    @HiBMlive 5 ปีที่แล้ว +14

    hey. thanks for the video. Would be great if you could either decrease the sound of the keyboard clicks or use a better microphone.

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

      BM BM just started using a better mic

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

    Passes 1560/1563 test cases.
    class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    StringBuilder s1 = new StringBuilder("");
    StringBuilder s2 = new StringBuilder("");
    while(l1!=null){
    s1.append(l1.val);
    l1 = l1.next;
    }
    while(l2!=null){
    s2.append(l2.val);
    l2 = l2.next;
    }
    String t1 = s1.reverse().toString();
    String t2 = s2.reverse().toString();
    long i1 = Long.parseLong(t1);
    long i2 = Long.parseLong(t2);
    long i3 = i1+i2;
    if(i3==0){
    return new ListNode(0);
    }
    ListNode dummy = new ListNode(-1);
    ListNode head = dummy;
    while(i3!=0){
    int k = (int)(i3%10);
    i3 = i3/10;
    head.next = new ListNode(k);
    head = head.next;
    }
    return dummy.next;
    }
    }

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

    Some how this was the only video that could explain the solution to me. thanks

  • @laurawu5146
    @laurawu5146 5 ปีที่แล้ว +10

    thanks for sharing. very clear explanation. Im preparing for my interview, I like your video

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

    is that capital one's hack t-shirt ur wearing?

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

      good eye! Yeah it is

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

    do we need line 36?

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

    Line 36 not needed?

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

      Yes, the answer would be accepted without the line 36 too.

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

    this solution doesn't work when the digital number is different, 999+1 and 999+100 are different result, you should reverse the list first

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

      yes it does work. the nodes are. 9->9->9->null and 0->0->1->null for 999+100 and 9->9->9->null and 1->null for 999+1. tested it. the results are 9->9->0->1->null and 0->0->0->1->null, respectively.

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

    Imo it’s more convenient (val_1 + val_2) % 10 further we can check if val_1 + val2 >= 10

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

    dang, you must've gotten a really good server since I keep getting "time limit exceeded" error. My code is very similar, I guess I got unlucky with the server being slow or something.

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

    how is the carry not being brought over from the first time? wouldn’t it be .7?

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

    Thank you brother for your explanation.

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

    wat about the 0 in the list during initialization wouldnt that lead to a wrong answer?

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

    What if we have much larger numbers? Sum must be long type right

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

    Hello, Thanks to sharing ur specious knowledge.
    But i got a error like "Time limit Exceeded".
    Please help me for the same.

    • @skm9865
      @skm9865 4 ปีที่แล้ว

      me too have you got any solution?

    • @aryaabhishek9535
      @aryaabhishek9535 4 ปีที่แล้ว

      @@skm9865 you have skipped the increment part i.e. incrementing l1, l2 , l3 check that

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

      @@aryaabhishek9535 I will check , thank you

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

      @@aryaabhishek9535 I still get the time limit exceed. I have the code verbatim :(

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

    He copies the solution code acting like he came up with it 😂.

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

    Really easy tutorial to follow, thanks a ton!

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

    This problem was so annoying

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

    can someone explain why the l3 = dummy_head?

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

    Thank u so much, Nick! it's very helpful. I finished mine in 1ms but my solution based on yours.^^

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

    bro thanks for the content

  • @ziakhan-tk7rk
    @ziakhan-tk7rk 4 ปีที่แล้ว +1

    Do you practice all problem beforehand and them present them here or is it you solve on the spot ??

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

      He knows the answer already

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

      obviously

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

    Did this using stacks? Not sure if it’s calid

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

    Please solve by ur own solution nick 😂

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

    whats written on line number 34 after listNode new_node = new ?

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

      ListNode new_node = new ListNode(carry);

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

    Halo Nick..where is the Java Souce GitHub URL for each problem?Please share

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

    What u worte in line 34 ?..not clear

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

    Thank you! This was the first time I was able to understand the solution to this problem.

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

    I like how dead his voice is.

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

    You could improve this further by doing it with O(1) space if you reuse nodes of the longer number

    • @AlbertoRodriguez-oe6jo
      @AlbertoRodriguez-oe6jo 3 ปีที่แล้ว +2

      It is not guaranteed if there even exists a longer node, say 99 + 99 = 198, and generally, changing the given parameters (ListNode* l1, ListNode* l2) is not the best practice.

    • @CD-xd6fm
      @CD-xd6fm 2 ปีที่แล้ว

      this wont work when their is carry over

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

      @@CD-xd6fm carryover is at most how many nodes? It's constant space.

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

      @@AlbertoRodriguez-oe6jo if you're trying to optimize for space then it's OK. Yes, in real life it's not the best practice to modify objects from the arguments. Also what I meant is either the longer one or just a random one of the two..

    • @CD-xd6fm
      @CD-xd6fm 2 ปีที่แล้ว

      @@coolilshat carry over is just one node.....but you were saying to overwrite the longer linked list...but let's say for e.g. 987+98 = 1085.....in this case you will need four nodes to store the answer but you are only having three

  • @An-Engineered-Journey
    @An-Engineered-Journey 2 ปีที่แล้ว +2

    I'm confused why we need all the null checks. Because we are doing l1 != null OR l2 != null in the while loop, if either of these 2 values are null wouldn't it break out of the loop and not execute so we know they would never be null ?

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

      This confused me too for a while. It's simple but a lot is going on so it is hard to understand right away. The while condition in English says: While *either* list is not null keep going. You are mistaking that for saying if either of the two list is null end the loop.
      Anyway this means that either:
      Both are null: The loop is done, print out our answer
      Both are not null: Easy, we just keep going
      One is null the other list has another number left : This is a bit trickier. i.e adding a list with 123 and the second list has = 1234, 123 would be null after 3, 1234 has "4" left. Thus list 1 is null list 2 still has another digit to go so the loop iterates one more time. After adding 4, both list are null we are done.
      Now what does the second null check do? As I stated in case 3 one can be null but the other not null. We can not add 123NULL and 1234NULL because they don't line up. So we must replace null with a 0 (as we would writing math with a paper and pencil in real life) to "line it up" so to say.
      *Reminder that the end of a list aka the tail is always null this is just a convention used so we know where to stop. *

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

      @@kakashi99908 Thank you for your explanation!! Was having the same doubt

  • @RANAND-xd3zu
    @RANAND-xd3zu 4 ปีที่แล้ว

    Nick offer(), and size() method what to do.please help me

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

    what happened on 4:05??

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

    Thanks

  • @kalpkumudkumar8163
    @kalpkumudkumar8163 4 ปีที่แล้ว

    please move you Pic at left Bottom corner

  • @AbhinavKumar-dr4ef
    @AbhinavKumar-dr4ef 2 ปีที่แล้ว

    I thought the same way. Thank you. You are awesome.

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

    coding made easy

  • @neeleshbhargav8987
    @neeleshbhargav8987 4 ปีที่แล้ว

    If in case of different size of list how it

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

    Thank you for all your videos! verry helpfull

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

    at first line of our code we are creating a null node right??

    • @dileshsolanki2383
      @dileshsolanki2383 4 ปีที่แล้ว

      it's just a dummy node with a dummy value 0

  • @lingsike3193
    @lingsike3193 5 ปีที่แล้ว

    Hi, I am just wondering that if the inputs params not linklist, they are 2 arrays, but one of them has longer length. how would you do this addition

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

      is there a leetcode problem you can link? I'll just make a video if you can find one

    • @lingsike3193
      @lingsike3193 5 ปีที่แล้ว

      @@NickWhite Hi Nick, this is just random question pop up in my head, I do not see one so far. For example, [1,2,3], [1,2,3,4]. if 2 array has same length it will be easy to do so. but if one of them has different length this will be interesting

    • @lingsike3193
      @lingsike3193 4 ปีที่แล้ว

      @Patrick K That is a good way, Thanks.

    • @hritwiksom3032
      @hritwiksom3032 4 ปีที่แล้ว

      @@lingsike3193 AFAIK arrays have fixed size in java and c++. You can't just add an element to it. Better would be to convert both arrays into a two numbers, add them, turn the answer to an array and return it.
      You can convert array to num using:
      int count = 1;
      for(int i=0; i

  • @7906jun
    @7906jun 4 ปีที่แล้ว +1

    Thank you sir.

    • @raktimranjandeka2793
      @raktimranjandeka2793 4 ปีที่แล้ว

      whats written on line number 34 after listNode new_node = new ?

  • @ayyubshaffy3612
    @ayyubshaffy3612 4 ปีที่แล้ว

    cool

  • @alvxlopez
    @alvxlopez 4 ปีที่แล้ว

    Thank you

  • @snake1625b
    @snake1625b 5 ปีที่แล้ว

    thanks!

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

    Hi Nick, I'm using your videos to compare my solutions on many problems. It helped me a lot. Thaks a lot. Your always comes up with a new and greater solution.

  • @gyanendrapratap7891
    @gyanendrapratap7891 4 ปีที่แล้ว

    dude could you please do solutions of codechef monthly challanges

  • @Mohammedaatif90
    @Mohammedaatif90 4 ปีที่แล้ว

    what if the numbers are in non reversed order?. We should reverse both list and do this approach ?

    • @SlideTackles
      @SlideTackles 4 ปีที่แล้ว

      write a reverse function pass list to it and then its all same

  • @jagritbhupal5836
    @jagritbhupal5836 4 ปีที่แล้ว

    Thanks, man.

    • @raktimranjandeka2793
      @raktimranjandeka2793 4 ปีที่แล้ว

      whats written on line number 34 after listNode new_node = new ?

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

      @@raktimranjandeka2793 new ListNode ( carry)

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

    cant understand the accent....smh

    • @NickWhite
      @NickWhite  5 ปีที่แล้ว +6

      rahul raj my bad dude it’s just English but I can try and annunciate better

    • @PoulJulle-wb9iu
      @PoulJulle-wb9iu 4 ปีที่แล้ว +8

      too bad he aint doing that hinde accent huh

    • @xaviersson7047
      @xaviersson7047 4 ปีที่แล้ว

      XD lmao