MediumNo. 2181

Merge Nodes in Between Zeros — LeetCode 2181 Python Solution

Topics
Linked List, Simulation
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

PythonSolution
# 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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
2326Spiral Matrix IVMedium
0019Remove Nth Node From End of ListMedium
0021Merge Two Sorted ListsEasy
0024Swap Nodes in PairsMedium
0025Reverse Nodes in k-GroupHard
0061Rotate ListMedium

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.

Free to download. Check it runs on your machine, then pick a plan.