LeetCode 2181: Merge Nodes in Between Zeros Solution
Master LeetCode problem 2181 (Merge Nodes in Between Zeros), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2181. Merge Nodes in Between Zeros
Problem Explanation
Explanation
To solve this problem, we can iterate over the linked list and whenever we encounter two consecutive zeros, we merge all the nodes between them by calculating the sum of their values. We update the pointers accordingly to skip the merged nodes. We continue this process until we reach the end of the linked list.
- Time complexity: O(n), where n is the number of nodes in the linked list.
- Space complexity: O(1) since we are modifying the original linked list in place.
Solution Code
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public ListNode mergeNodesInBetweenZeros(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
while (prev != null && prev.next != null) {
ListNode start = prev.next;
ListNode end = start;
int sum = 0;
while (end != null && end.val != 0) {
sum += end.val;
end = end.next;
}
if (end != null && end.next != null && end.next.val == 0) {
prev.next = new ListNode(sum);
prev.next.next = end.next.next;
}
prev = prev.next;
}
return dummy.next;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2181 (Merge Nodes in Between Zeros)?
This page provides optimized solutions for LeetCode problem 2181 (Merge Nodes in Between Zeros) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2181 (Merge Nodes in Between Zeros)?
The time complexity for LeetCode 2181 (Merge Nodes in Between Zeros) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2181 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2181 in Java, C++, or Python.