Merge Nodes in Between Zeros — LeetCode 2181 Python Solution

MediumLinked ListSimulation
Problem
#2181
Reading time
4 min

The 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.

Example

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

Python solution

Python
# 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]:
        dummy = tail = ListNode()
        s = 0
        cur = head.next
        while cur:
            if cur.val:
                s += cur.val
            else:
                tail.next = ListNode(s)
                tail = tail.next
                s = 0
            cur = cur.next
        return dummy.next

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 2181. Merge Nodes in Between Zeros is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2181. Merge Nodes in Between Zeros?
LeetCode 2181. Merge Nodes in Between Zeros is rated Medium on LeetCode.
What is the time complexity of LeetCode 2181. Merge Nodes in Between Zeros?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2181. Merge Nodes in Between Zeros?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2181. Merge Nodes in Between Zeros cover?
LeetCode 2181. Merge Nodes in Between Zeros is tagged Linked List and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview