DDSA
Advertisement

2181. Merge Nodes in Between Zeros

Time: O(n)
Space: O(1)

Approach

Single pass; accumulate values between 0-nodes and write sums into new list.

2181.cs
C#
// Approach: Single pass; accumulate values between 0-nodes and write sums into new list.
// Time: O(n) Space: O(1)

public class ListNode
{
    public int val;
    public ListNode next;
    public ListNode(int val = 0, ListNode next = null)
    {
        this.val = val;
        this.next = next;
    }
}

public class Solution
{
    public ListNode MergeNodes(ListNode head)
    {
        ListNode curr = head.next;

        while (curr != null)
        {
            ListNode running = curr;
            int sum = 0;
            while (running.val > 0)
            {
                sum += running.val;
                running = running.next;
            }

            curr.val = sum;
            curr.next = running.next;
            curr = curr.next;
        }

        return head.next;
    }
}
Advertisement
Was this solution helpful?