Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2181: Merge Nodes in Between Zeros

In this guide, we solve Leetcode #2181 Merge Nodes in Between Zeros in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Linked List, Simulation

Intuition

Linked list problems often require pointer manipulation rather than extra memory.

Two-pointer techniques expose cycles, midpoints, or reordering patterns.

Approach

Traverse with fast/slow pointers or reverse sublists when needed.

Maintain invariants carefully to avoid losing nodes.

Steps:

  • Traverse with pointers.
  • Reverse or split if required.
  • Reconnect nodes correctly.

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 - The sum of the nodes marked in green: 3 + 1 = 4. - The sum of the nodes marked in red: 4 + 5 + 2 = 11.

Python Solution

# 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

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy