Add Two Numbers (LeetCode 2) | Full solution with diagrams | EASIEST EVER | Study Algorithms

แชร์
ฝัง
  • เผยแพร่เมื่อ 1 ก.ค. 2024
  • To see more videos like this, you can buy me a coffee: www.buymeacoffee.com/studyalg...
    Actual Problem: leetcode.com/problems/add-two...
    Chapters:
    00:00 - Intro
    00:56 - Problem Statement and Description
    03:50 - Edge cases and things to be careful about
    06:01 - Defining a Solution
    08:26 - Dry-run of Code
    12:08 - Final Thoughts
    📚 Links to topics I talk about in the video:
    Linked Lists: • Linked List Data Struc...
    Traversing Linked Lists: • Traversing a Linked Li...
    📘 A text based explanation is available at: studyalgorithms.com
    Code on Github: github.com/nikoo28/java-solut...
    Test-cases on Github: github.com/nikoo28/java-solut...
    📖 Reference Books:
    Starting Learn to Code: amzn.to/36pU0JO
    Favorite book to understand algorithms: amzn.to/39w3YLS
    Favorite book for data structures: amzn.to/3oAVBTk
    Get started for interview preparation: amzn.to/39ysbkJ
    🎥 My Recording Gear:
    Recording Light: amzn.to/3pAqh8O
    Microphone: amzn.to/2MCX7qU
    Recording Camera: amzn.to/3alg9Ky
    Tablet to sketch and draw: amzn.to/3pM6Bi4
    Surface Pen: amzn.to/3pv6tTs
    Laptop to edit videos: amzn.to/2LYpMqn
    💻 Get Social 💻
    Follow on Facebook at: / studyalgos
    Follow on Twitter at: / studyalgorithms
    Follow on Tumblr at: / studyalgos
    Subscribe to RSS feeds: studyalgorithms.com/feed/
    Join fan mail: eepurl.com/g9Dadv
    #leetcode #programming #interview

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

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

    Just want to say, thank you for covering this in the clean format that you did, this made the video engaging. Keep up these amazing videos.

  • @johncho9160
    @johncho9160 5 หลายเดือนก่อน +3

    i really enjoy your leetcode explanations with the dry run of the code. as somone prepping for interviews, youve helped me a lot. thankyou!!!

  • @anujgupta1484
    @anujgupta1484 6 หลายเดือนก่อน +2

    you are truly a gem for DSA learners .

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

    Your solution made the most sense to me. Thanks!

  • @JigneshPatel-c8z
    @JigneshPatel-c8z 9 หลายเดือนก่อน

    This is the best and clearest explanation of a leetcode problem that I have ever seen !!!

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

    Really easy to understand explanation and the best I have seen for this problem, thank you so much!

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

    Really enjoyed this video! Been following your channel to learn how to solve leetcode questions and your videos and organization are super useful and well thought out. Keep it up!

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

      You're very welcome!

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

    this was a beautiful explanation. Thank you

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

    very clear explanation brother ..I so great to find your videos

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

    bruh you are awesome not even get bored while watching
    thanks

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

    Thank you !
    You make best explanations :)

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

    Good work, Keep it up!

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

    Very well explained. Thanks

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

    Your leet code solutions are above the par and the explaination is the deadly combination

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

      So happy to hear that :)

  • @KRajesh-ej7dy
    @KRajesh-ej7dy ปีที่แล้ว +1

    I Felt Happy After Listening This
    Thank You Bro

  • @ToireasaMoley-mk3tw
    @ToireasaMoley-mk3tw 6 หลายเดือนก่อน

    great explanation! so easy to follow :)

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

    Thank you brother your explanation is amazing . i understood this problem very clearly

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

    You deserve many more subscribers 😃Concise and accurate explanation.
    No confusion, every point makes sense. Please keep up the good work. 👍

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

      Trying hard 😇

  • @joaoguilherme-or1ud
    @joaoguilherme-or1ud หลายเดือนก่อน

    Muito Obrigado por essa Explicação fantastica !!!

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

    You are really teaching amazing sir, I can undestand very clearly❤

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

    nice explanation, got understood the solution in one video of yours,despite searching others

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

      glad you found it helpful

  • @jean-paulboga8189
    @jean-paulboga8189 6 หลายเดือนก่อน +1

    thanks for the great explanation.

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

    Beautiful explanation..🔥🔥

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

    super broo this is one of the best and easy solution i have ever seen thank you so much for this solution its really helpful🤩🤩😍😍👏👏

  • @jmajid774
    @jmajid774 21 วันที่ผ่านมา

    Thanks. very cool video

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

    awesome explanation bro

  • @No-Nama-_-.0
    @No-Nama-_-.0 หลายเดือนก่อน +1

    Thankyou sir 😊😊

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

    understood thanks !

  • @PrashantKumar-fk8le
    @PrashantKumar-fk8le 10 หลายเดือนก่อน

    This man explains Best of best on youtube,Huge Salute 👑👑👑👑

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

      so glad you feel this way.

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

    explained simply! thank you

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

      Glad it was helpful!

  • @Anuli-Edom
    @Anuli-Edom 8 หลายเดือนก่อน

    Best explanation to this i have seen so far

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

      yay!!

  • @itkavyas.p6176
    @itkavyas.p6176 7 หลายเดือนก่อน

    i just started DSA as beginner after watching most of the solution your solution is very simple and easy please post more videos and support peoples ..... you earned the new subscriber

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

      thanks for the sub 😄

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

    Thanks a lot for this simple and easy solution. I solved the problem but test case 1565 out of 1568 was my stuck point and after that, I found your video. Keep up the excellent work.

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

      Well done

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

    i really appreciate you sharing solution and telling how converting linked list into integers then adding and then again converting into linked list method is inefficient as thats what came in my mind while first solving solution

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

      glad you found it helpful

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

    Amazing content bro keep going, only time is your enemy, just wait for some time and you will reach to new heights.

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

      Hope so

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

    Частично понимал перевод, но за счет очень классного визуального объяснения понял объясняемый алгоритм. Круто, спасибо, было интересно

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

      Я так рада, что смогла вам помочь.

  • @krishankantsaraswat2276
    @krishankantsaraswat2276 24 วันที่ผ่านมา

    00:02 Adding two numbers in linked list format with reversed order
    01:39 Adding two reversed numbers represented as linked lists.
    03:27 Handle zeros at the beginning of linked lists while adding numbers.
    05:06 Carefully consider edge cases for adding large numbers and handling overflow.
    06:45 Adding two numbers using pointers and carrying over.
    08:23 Code implementation and algorithm explanation
    10:02 Splitting out the sum and carry after adding two numbers
    11:47 Understanding the time and space complexity of the solution
    Crafted by Merlin AI.

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

    thanks for the explanation.

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

    Thank you

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

    nicely explained ,thank you

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

      Glad it was helpful!

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

    thanku so much

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

    Thanks

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

    Always we search for nikil's leetcode solution ❤😅

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

      wow...I am grateful for that.

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

    Worth the time

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

      appreciate your feedback

  • @SinchannDekesuki
    @SinchannDekesuki 15 วันที่ผ่านมา

    i have a doubt in this question i was able to solve this problem without using any extra space after that i saw many sloution just to know different approach most of them are creating new linked list which is extra space i have stored my result in the linkedlist which has max length of question it is right to do so ? or i shouldn't modify the question's linked list..

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

    thank u so much.your explanation is quite simple

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

      Happy to help

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

      @@nikoo28 but why not all medium questions in leetcode have videos.i suggest to increase number of medium questions

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

      @@mennahassan5828 It takes time to create quality content. I take almost a total of 10 hours to create one video with proper thumbnails, companies that it has been asked in, github links, thumbnails, editing etc. etc.. I also try to upload the content in full 4K quality for best viewing experience.
      Nonetheless, stay tuned...I am constantly trying to cover more and more important questions as time permits :)

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

      @@nikoo28 thank you so much.appreciated

  • @pankajyadav-en7tb
    @pankajyadav-en7tb 7 หลายเดือนก่อน +1

    Wow!!.

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

    Great explanation! Could you please explain how result contains the numbers if we're only assigning the numbers in the next for the ptr?

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

      the result does not contains numbers, it contains a linked list, that has the answer numbers. That is what the question asks as well :)

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

      @nikoo28 I understand, I used nunbers by mistake. What I meant is how does it contain the full linked list if we're only updating the ptr linked list? Hope that clears up the question!

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

      It still has single digits, you will have to interpret/construct the number from the list

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

    sir suppose in the last Iteration carry is more than one than what happens. in your code how can you decide carry is one... ?

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

      when you are adding 2 single digits, the carry can never be more than 1 :)

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

      I had the same question but, two single digits can't have carry more than 1

  • @user-oj8ey7wc2n
    @user-oj8ey7wc2n 29 วันที่ผ่านมา

    why we should add sum in the ptr.next?in think we should add in ptr.next.val ?

    • @nikoo28
      @nikoo28  27 วันที่ผ่านมา

      can you tell me the timestamp you are referring to?

  • @user-um2tl3mn5t
    @user-um2tl3mn5t 5 หลายเดือนก่อน

    In the above case missing some test cases when both linked sizes are not the same that time above code will not work. Other your explanation is superb. add this code and sum variable will be global while(l2 != null){
    sum = 0 + carry;
    sum += l2.val;
    l2 = l2.next;
    carry = sum / 10;
    sum = sum % 10;
    ptr.next = new ListNode(sum);
    ptr = ptr.next;
    }
    while(l1 != null){
    sum = 0 + carry;
    sum += l1.val;
    l1 = l1.next;
    carry = sum / 10;
    sum = sum % 10;
    ptr.next = new ListNode(sum);
    ptr = ptr.next;
    }

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

      It will work, did you check the code available on Github?

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

    it was really helpful. thank you. just wanted to say that if the audio was clear it would have been more convenient, as ur voice feels like an echo. overall thanks

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

    In problem values are 5 and 2 are giving for sum then ?
    carry = sum /10; -> 7/10 = 0.7;
    why sum is saving -> sum %10 ??
    any one know ?

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

    Wouldn’t the first element in your solution node (zero) affect the final result? I didn’t get that

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

      In the provided code, the initial node with value 0 is actually a placeholder node. This is a common technique used in linked list problems to simplify the code and avoid special cases at the beginning of the list. It doesn't affect the final result of the summation.
      As the code processes the linked lists l1 and l2, the actual result is constructed starting from the node after the placeholder node. This is why, throughout the loop, new nodes are added after the placeholder node (since the code initializes ptr as result).
      The code returns result.next, which is the node immediately after the placeholder node. This is the correct starting point for the final result linked list.

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

    How will this eliminate the problem of test cases of very large numbers?

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

      because you are using linked lists. Each node will have only 1 digits. So your number can have 1000 digits, and still you will be able to add

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

    Amazing bro keep going!! Love what you're doing. How can I contact you pls?

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

      You can contact me via e-mail. It is available in the "About" section of my channel :)

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

    can you help do this type of question solution

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

      can you please elaborate?

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

    Great tutorial. Just a small suggestion. int sum = 0 + carry; Is this needed? If 0 is going to be added every time in the loop we can just ignore it and write it like int sum = carry. I tried and it worked. Only if we need to add sum to sum then we need to write like int sum = sum + carry; otherwise I feel the 0 is redundant. Your thoughts on this please!!!

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

      0 + carry just seems familiar with what we are doing in the future. Makes your code more readable.

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

    Hey bro i have a quesiton, why result next have the sum of ptr have add? I don't understand and question 2 is why you return head next instead of ptr next? Hmm maybe ptr next just a single node and result next all the node that ptr next have? Why result have all the sum that ptr next add, hmmm can you explain

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

      can you explain your question with an example? I am unable to follow your doubt.

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

      Its mean brother you're so good, understand that brother 😂😆

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

    This is a question for this problem. if l1 has more nodes than l2, then l2 next node is null. if number+null, we will get null? We should consider this situation. is it?

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

      check the problem constraints. You may need to modify your code accordingly :)

  • @anubhav.codess
    @anubhav.codess 6 หลายเดือนก่อน

    if(carry>0)
    {
    ptr.next=new Node(carry);
    }
    what if the value of carry is 2 or 3 or 4 ?

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

      When you add 2 digits, can the value of carry ever be more than 1 ??

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

    I dont understand why when we return result.next we get something iw we didnt add anything in it.

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

      result.next has the complete linked list

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

      @@nikoo28 Thank you, I figured it out after some time.

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

    Yet another dsa channel. Same story different actor

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

    code didn't worked on leetcode man what to do ?

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

      that is not possible. try the code available on github (link in description)

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

    Bro can you explain same problem by using python

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

      the logic will remain the same, it gets a little hard to solve for every language

  • @arijitmalakar6911
    @arijitmalakar6911 17 ชั่วโมงที่ผ่านมา

    This solution is giving "time limit exceeded" error n leetcode...

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

    praise lord ganesh

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

      🙏

  • @usmanrangrez-cd7zj
    @usmanrangrez-cd7zj 11 หลายเดือนก่อน

    class Solution {
    public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode *ans = new ListNode(0);
    ListNode *curr=ans;
    ListNode *p=l1;
    ListNode *q=l2;
    int carry = 0;
    while(p!=NULL || q!=NULL){
    int firstData = (p!=NULL)?p->val:0;
    int secondData = (q!=NULL)?q->val:0;
    int sum=firstData+secondData+carry;
    carry=sum/10;
    int toPut = sum%10;
    curr->next = new ListNode(toPut);
    curr=curr->next;
    if(p!=NULL) p = p->next;
    if(q!=NULL) q = q->next;
    }
    //end pe agar carry milega 1
    if(carry>0){
    curr->next = new ListNode(carry);
    }
    return ans->next;
    }
    };
    Different Approach

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

    Which language has he used?

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

      JAVA

  • @code-Dude
    @code-Dude 3 หลายเดือนก่อน

    can someone help me
    /**
    * 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 addTwoNumbers(ListNode l1, ListNode l2) {
    l1 = revesrseLL(l1);
    l2 = revesrseLL(l2);


    ListNode head = new ListNode(0);
    ListNode temp = head;
    int carry = 0;
    while( l1 != null || l2 != null ){
    int sum = carry;
    if(l1 != null){
    sum = sum + l1.val;
    l1 = l1.next;
    }
    if(l2 != null){
    sum = sum + l2.val;
    l2 = l2.next;
    }
    //check carry and sum
    carry = sum / 10;
    sum = sum % 10;
    temp.next = new ListNode(sum);
    temp = temp.next;
    sum = 0;
    }
    if(carry==1){
    temp.next = new ListNode(1);
    }



    return head.next;

    }
    public ListNode revesrseLL(ListNode head) {
    ListNode pre = null;
    ListNode cur = head;
    ListNode nxt;
    while (cur != null) {
    nxt = cur.next;
    cur.next = pre;
    pre = cur;
    cur = nxt;
    }
    return pre;
    }
    }

  • @honey-xr5kp
    @honey-xr5kp 2 หลายเดือนก่อน

    I must be doing something wrong, but all my test cases come back as wrong with this code.

    • @honey-xr5kp
      @honey-xr5kp 2 หลายเดือนก่อน

      It adds an extra 0 to the beginning of the list each time. I'm not sure how or why?

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

      Did you have a look at the code given in video description?