Skip to content

Merge Nodes in Between Zeros

Leetcode 2181. Merge Nodes in Between Zeros

Leetcode 2181: Merge Nodes in Between Zeros

Problem

You are given the head of a linked list, which contains a series of integers separated by 0‘s. The beginning and end of the linked list will have Node.val == 0.

For every two consecutive 0‘s, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0‘s.

Return the head of the modified linked list.

Example 1:

Input: head = [0,3,1,0,4,5,2,0]
Output: [4,11]
Explanation: 
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 3 + 1 = 4.
- The sum of the nodes marked in red: 4 + 5 + 2 = 11.

Example 2:

Input: head = [0,1,0,3,0,2,2,0]
Output: [1,3,4]
Explanation: 
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 1 = 1.
- The sum of the nodes marked in red: 3 = 3.
- The sum of the nodes marked in yellow: 2 + 2 = 4.

Constraints:

  • The number of nodes in the list is in the range [3, 2 * 105].
  • 0 <= Node.val <= 1000
  • There are no two consecutive nodes with Node.val == 0.
  • The beginning and end of the linked list have Node.val == 0.

Soure: Leetcode 2181. Merge Nodes in Between Zeros

Solution
Analysis

Let’s take an input list like [0, 2, 7, 0, 5, 1, 0].

We can solve this problem with additional two pointers. Let’s assume the head pointer of the given linked list is the owner or boss of the linked list. He employed a manager whose name is local_node. He also hired a worker named temp to work under local_node. As a first quick step, we can move head to point to its next node since the first node is always zero. We will do this forward movement of head before assigning local_node and temp to point head.

Now, after head pointed to its next node, ocal_node and temp are created and they assigned value of head. So, at this point head, local_node and temp are all pointing to the second node of the linked list as the image below.

Leetcode 2181: Merge Nodes in Between Zeros
Leetcode 2181: Merge Nodes in Between Zeros — all standing at the second node

The job of temp node is to move forward and sum up all the non zero values and keep the sum in a variable sum (we used variable name _sum in the Python code to avoid conflict with Python’s built-in sum function). After traversing and summing, when temp points to the next zero node, local_head takes the sum and update itself. See the next image to understand this.

Leetcode 2181: Merge Nodes in Between Zeros
Leetcode 2181: Merge Nodes in Between Zeros — local_head’s value is updated by sum

Then it updates its next pointer to point to the next pointer of temp as shown in the image below.

Leetcode 2181: Merge Nodes in Between Zeros
Leetcode 2181: Merge Nodes in Between Zeros — local_head next points to temp next

Remember, temp is now pointing to a zero, the next pointer of temp is pointing to either NULL or a non-zero element. At this point, temp will move forward as below image.

Leetcode 2181: Merge Nodes in Between Zeros
Leetcode 2181: Merge Nodes in Between Zeros — temp moves forward

All we need now is to move local_head forward. Since local_hed‘s next was pointing to the next of temp‘s previous position (where temp is pointing now), at this stage both of them will point to the same node. Finally, sum will be reinitialized to zero. Below image shows the final stage after one merge happens.

Leetcode 2181: Merge Nodes in Between Zeros
Leetcode 2181: Merge Nodes in Between Zeros — steps to move forward

You see here we didn’t use any additional space to store the entire linked list. Nodes that are not used anymore, for example, 7 and 0 will remain as dangling nodes. From the steps so far, we can see that, head is still pointing to a node which is the merge result of non-zero elements. If we follow these steps to the entire linked list, we will get the output list = [9, 6].

Below are codes that explains the process. If you find it difficult to understand the algorithm, please try to think about it for some time, come back to this post and re-read the explanation. Hope that will help 🙂

C++ code
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeNodes(ListNode* head) {
        //First value is zero, so we can omit that
        if(head->val==0)
            head = head->next;
        
        ListNode* local_head = head; // local_head will contain result(sum) of merged nodes
        ListNode* temp = head; // temp will help to traverse the linked list
        int sum = 0;
        
        while(temp != NULL){
            if(temp->val != 0){ 
                sum += temp->val; //node is not 0, so we sum up
                temp = temp->next;//and move forward
            }
            else{
                local_head->val = sum; //we have the sum upto this point, we now update local_head's value
                local_head->next = temp->next; //local_head no need to point to its original next element, it will point to the next of temp now
                temp = temp->next;
                local_head = local_head->next;
                sum = 0;
            }
        }
        
        return head;
    }
};
Java code
class Solution {
    public ListNode mergeNodes(ListNode head) {
        //First value is zero, so we can omit that
        if(head.val==0)
            head = head.next;
        
        ListNode local_head = head; // local_head will contain result(sum) of merged nodes
        ListNode temp = head; // temp will help to traverse the linked list
        int sum = 0;
        
        while(temp != null){
            if(temp.val != 0){ 
                sum += temp.val; //node is not 0, so we sum up
                temp = temp.next;//and move forward
            }
            else{
                local_head.val = sum; //we have the sum upto this point, we now update final_head's value
                local_head.next = temp.next; //final_head no need to point to its original next element, it will point to the next of temp now
                temp = temp.next;
                local_head = local_head.next;
                sum = 0;
            }
        }
        
        return head;
    }
}
Python code
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head.val == 0:
            head = head.next
        local_head = head #local_head will contain result(sum) of merged nodes
        temp = head       #temp will help to traverse the linked list
        _sum = 0
        
        while temp is not None:
            if temp.val is not 0:
                _sum += temp.val #node is not 0, so we sum up
                temp = temp.next #and move forward
            else:
                local_head.val = _sum #we have the sum upto this point, we now update local_head's value
                local_head.next = temp.next #local_head now doesn't need to point to its original next element, it will point to the next of temp now
                temp = temp.next #move temp forward
                local_head = local_head.next #move local_head forward
                _sum = 0 #reset _sum to 0
        
        return head
        
Javascript code
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var mergeNodes = function(head) {
    //First value is zero, so we can omit that
        if(head.val==0)
            head = head.next;
        
        let local_head = head; // local_head will contain result(sum) of merged nodes
        let temp = head; // temp will help to traverse the linked list
        let sum = 0;
        
        while(temp != null){
            if(temp.val != 0){ 
                sum += temp.val; //node is not 0, so we sum up
                temp = temp.next;//and move forward
            }
            else{
                local_head.val = sum; //we have the sum upto this point, we now update final_head's value
                local_head.next = temp.next; //final_head no need to point to its original next element, it will point to the next of temp now
                temp = temp.next;
                local_head = local_head.next;
                sum = 0;
            }
        }
        
        return head;
};
Time and Space Complexity

Time – O(N), since we are traversing the entire list

Space – O(1), we are not using any extra space that will grow proportionate to the input size.

Conclusion

Hope this post helped you understand the solution of Leetcode 2181: Merge Nodes in Between Zeros. If you like it or hate it, please post some comments so that we can improve our writing or get motivation! Happy Coding!

ByteByteGo is by far the best system design resource found on the internet. They are growing like crazy!

We suggest you checkout their course if you really want to dive deep in system design and want to have a killer interview!

Here is the link: ByteByteGo!

Disclaimer: this is a genuine suggestion, but we have some interest too! We get commission if you buy their course. However, there are other courses online which we do not promote. Because we promote only things that are the best in our opinion and those we really feel will be helpful for you.

102 thoughts on “Merge Nodes in Between Zeros”

  1. What’s up to every body, it’s my first go to see of this website; this webpage carries awesome and in fact good data in support of
    readers.

  2. Heya are using WordPress for your site platform? I’m new to the blog world but
    I’m trying to get started and set up my own. Do you require any html coding knowledge to make your own blog?
    Any help would be greatly appreciated!

  3. I like what you guys are usually up too. This kind of clever work and coverage!

    Keep up the very good works guys I’ve included
    you guys to my blogroll.

  4. Hello, Neat post. There’s a problem together with your site in web explorer, would test this?

    IE nonetheless is the marketplace leader and a big element
    of folks will miss your great writing because of this problem.

  5. Admiring the commitment you put into your site and in depth information you
    present. It’s good to come across a blog every once in a while that isn’t the same unwanted rehashed material.
    Excellent read! I’ve saved your site and I’m adding your RSS feeds to my Google account.

  6. At this time it seems like BlogEngine is the top blogging
    platform available right now. (from what I’ve read) Is that what you’re using
    on your blog?

  7. Thank you for another fantastic post. Where else may just anyone get that kind of information in such an ideal manner of writing?
    I have a presentation subsequent week, and I am at the search for such information.

  8. Hey! Would you mind if I share your blog with my twitter group?
    There’s a lot of people that I think would really enjoy your content.
    Please let me know. Thank you

  9. Great post however , I was wanting to know if you could write a litte more on this subject?
    I’d be very thankful if you could elaborate a little bit more.

    Bless you!

  10. Undeniably imagine that that you stated. Your favourite reason appeared to be on the web the easiest factor to have in mind of.
    I say to you, I certainly get annoyed while other folks consider worries that they plainly don’t recognize about.
    You managed to hit the nail upon the highest as smartly as defined out the
    entire thing with no need side-effects , people can take
    a signal. Will likely be back to get more. Thank you

  11. I’m not that much of a online reader to
    be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your site to come back later.
    Many thanks

  12. Hello very cool blog!! Guy .. Excellent .. Amazing ..
    I will bookmark your web site and take the feeds also?
    I am satisfied to find so many helpful information right here within the
    submit, we want develop extra techniques on this regard, thanks for sharing.
    . . . . .

  13. Hi there this is kind of of off topic but I was wondering if
    blogs use WYSIWYG editors or if you have to manually
    code with HTML. I’m starting a blog soon but have
    no coding expertise so I wanted to get guidance from someone with experience.

    Any help would be enormously appreciated!

  14. Heya i’m for the primary time here. I found this board and I to find It truly useful & it helped me out much.
    I hope to offer one thing back and help others such as you helped me.

  15. Hi are using WordPress for your blog platform?
    I’m new to the blog world but I’m trying to get started and create my own. Do you require any html
    coding knowledge to make your own blog? Any
    help would be really appreciated!

  16. Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you.

  17. I am currently writing a paper that is very related to your content. I read your article and I have some questions. I would like to ask you. Can you answer me? I’ll keep an eye out for your reply. 20bet

  18. You helped me a lot with this post. I love the subject and I hope you continue to write excellent articles like this.

  19. Great beat ! I would like to apprentice while you amend your web site, how could i subscribe for a blog site? The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear concept

  20. Thanks for posting. I really enjoyed reading it, especially because it addressed my problem. It helped me a lot and I hope it will help others too.

  21. Good day! This is kind of off topic but
    I need some advice from an established blog.
    Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick.
    I’m thinking about creating my own but I’m not sure where to
    begin. Do you have any points or suggestions? Cheers

  22. Hey there! Quick question that’s totally off topic. Do you know how to make your site mobile friendly?

    My web site looks weird when viewing from my iphone
    4. I’m trying to find a theme or plugin that might be able to fix this issue.
    If you have any recommendations, please share. Thank you!

  23. Hi I am so glad I found your web site, I really found you by accident, while I was browsing on Askjeeve for something else, Regardless I
    am here now and would just like to say many thanks for a marvelous post
    and a all round enjoyable blog (I also love the theme/design),
    I don’t have time to read it all at the minute but I have saved
    it and also added your RSS feeds, so when I have time I will
    be back to read a lot more, Please do keep up the
    awesome work.

  24. I was excited to discover this website. I want to to thank you for your time due to
    this wonderful read!! I definitely loved every bit of it and i also have you bookmarked to see new things in your
    blog.

  25. Thanks for posting. I really enjoyed reading it, especially because it addressed my problem. It helped me a lot and I hope it will help others too.

  26. Excellent items from you, man. I have take note your stuff previous to and you are
    just extremely fantastic. I really like what you have received right here,
    really like what you’re saying and the way in which
    wherein you are saying it. You make it entertaining and you still
    take care of to stay it sensible. I can’t wait to read much more from you.
    This is really a wonderful site.

  27. Wow that was strange. I just wrote an very long comment but
    after I clicked submit my comment didn’t appear. Grrrr…

    well I’m not writing all that over again. Regardless, just wanted to
    say excellent blog!

  28. Thanks for the article. I have generally seen that a majority of people are wanting to lose weight simply because wish to show up slim as well as attractive. Even so, they do not generally realize that there are many benefits just for losing weight additionally. Doctors assert that over weight people experience a variety of health conditions that can be directly attributed to their excess weight. Fortunately that people who sadly are overweight along with suffering from different diseases can reduce the severity of the illnesses simply by losing weight. You possibly can see a slow but noted improvement in health whenever even a bit of a amount of weight loss is obtained.

  29. I used to be very pleased to search out this web-site.I needed to thanks for your time for this excellent learn!! I undoubtedly having fun with every little little bit of it and I’ve you bookmarked to check out new stuff you blog post.

  30. I’m usually to blogging and i really admire your content. The article has actually peaks my interest. I’m going to bookmark your web site and maintain checking for new information.

  31. Excellent weblog here! Also your web site quite a bit up fast! What host are you the use of? Can I get your affiliate link for your host? I want my website loaded up as fast as yours lol

  32. I delight in, cause I found just what I used to be looking for. You have ended my 4 day lengthy hunt! God Bless you man. Have a nice day. Bye

  33. Pretty section of content. I simply stumbled upon your website and in accession capital to say that I acquire actually enjoyed account your blog posts. Any way I抣l be subscribing to your augment and even I fulfillment you get entry to constantly quickly.

  34. I抳e read some just right stuff here. Certainly value bookmarking for revisiting. I surprise how much attempt you put to make such a wonderful informative site.

  35. It is in reality a great and helpful piece of information. I am happy that you just shared this helpful information with us. Please stay us up to date like this. Thank you for sharing.

  36. Heya i抦 for the first time here. I found this board and I find It really useful & it helped me out much. I hope to give something back and help others like you helped me.

  37. I’m not sure exactly why but this website is loading extremely slow for me. Is anyone else having this issue or is it a issue on my end? I’ll check back later on and see if the problem still exists.

  38. Hi, Neat post. There’s a problem with your web site in internet explorer, would test this?IE still is the market leader and a big portion of people will miss your fantastic writing due to this problem.

  39. You completed some fine points there. I did a search on the theme and found most persons will agree with your blog.

  40. Hey there! Do you know if they make any plugins to assist with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success. If you know of any please share. Appreciate it!

  41. I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on few general things, The site style is wonderful, the articles is really excellent : D. Good job, cheers

  42. Hello foolishhungry.com webmaster, Your posts are always well-supported by research and data.

  43. Hello, I think your blog might be having browser compatibility issues.
    When I look at your blog in Safari, it looks fine but when opening
    in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up!
    Other then that, very good blog!

  44. This design is steller! You definitely know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Great job. I really loved what you had to say, and more than that, how you presented it. Too cool!

  45. Generally I do not learn post on blogs, but I would like to say that this write-up very forced me to take a look at and do it! Your writing taste has been surprised me. Thanks, very great post.

  46. F*ckin?tremendous things here. I am very glad to see your article. Thanks a lot and i’m looking forward to contact you. Will you please drop me a e-mail?

  47. I believe that avoiding processed foods will be the first step to lose weight. They may taste excellent, but prepared foods currently have very little nutritional value, making you take more just to have enough vitality to get through the day. When you are constantly consuming these foods, changing to whole grain products and other complex carbohydrates will aid you to have more vigor while feeding on less. Thanks alot : ) for your blog post.

  48. Good day! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

  49. Really Appreciate this blog post, how can I make is so that I receive an email sent to me when you write a fresh update?

  50. Hi foolishhungry.com administrator, Thanks for the informative and well-written post!

  51. Fantastic site. Lots of useful info here. I抦 sending it to some buddies ans additionally sharing in delicious. And of course, thank you for your effort!

  52. Its such as you read my mind! You appear to know a lot about this, like you wrote the e-book in it or something. I think that you just could do with some to force the message home a bit, however instead of that, that is magnificent blog. A great read. I will certainly be back.

  53. Thank you, I have recently been looking for information approximately this topic for ages and yours is the best I have discovered till now. However, what in regards to the bottom line? Are you sure in regards to the source?

  54. Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but other than that, this is great blog. A great read. I’ll certainly be back.

  55. You really make it seem so easy with your presentation but I find this matter to be actually something that I think I would never understand. It seems too complicated and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it!

  56. Thanks for another excellent post. Where else could anybody get that type of information in such an ideal way of writing? I’ve a presentation next week, and I am on the look for such info.

  57. Have you ever thought about adding a little bit more than just your articles? I mean, what you say is fundamental and everything. But just imagine if you added some great images or videos to give your posts more, “pop”! Your content is excellent but with pics and videos, this website could definitely be one of the best in its field. Excellent blog!

  58. I am not sure where you are getting your information, but great topic. I needs to spend some time learning more or understanding more. Thanks for magnificent info I was looking for this info for my mission.

  59. I’m also writing to make you know what a extraordinary encounter my cousin’s princess went through reading through your blog. She realized a lot of details, not to mention what it is like to possess an excellent helping style to have many people smoothly learn about several extremely tough topics. You undoubtedly surpassed visitors’ expected results. Thanks for imparting such valuable, trustworthy, educational as well as fun thoughts on your topic to Kate.

  60. I抦 not sure where you are getting your information, but good topic. I needs to spend some time learning much more or understanding more. Thanks for fantastic information I was looking for this information for my mission.

Leave a Reply

Your email address will not be published. Required fields are marked *