Skip to content

Commit a6ab788

Browse files
Adding my notes + solution for 2181
1 parent 7739403 commit a6ab788

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

problems/2181/jeremy.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# [Problem 2181: Merge Nodes in Between Zeros](https://leetcode.com/problems/merge-nodes-in-between-zeros/description/)
2+
3+
## Initial thoughts (stream-of-consciousness)
4+
- This seems pretty straightforward...
5+
- I think we can just keep a running sum of the nodes since the previous zero
6+
- Then once we hit another zero, set the value of the current node to the sum
7+
- If there are no more nodes, return the head node
8+
- Any edge cases to consider?
9+
- If there are two 0s in a row, what should we do? It looks like that case is not allowed.
10+
- We also don't need to account for lists that don't have any closing 0s, since the list length must be greater than or equal to 3 and the first and last values are guaranteed to be 0.
11+
12+
## Refining the problem
13+
- I think we can solve this in $O(n)$ time (where $n$ is the number of nodes in the original linked list)
14+
15+
## Attempted solution(s)
16+
17+
```python
18+
class ListNode:
19+
def __init__(self, val=0, next=None):
20+
self.val = val
21+
self.next = next
22+
23+
class Solution:
24+
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
25+
x = 0
26+
new_head = ListNode()
27+
current = new_head
28+
29+
n = head.next
30+
while n.next is not None:
31+
if n.val == 0:
32+
current.val = x
33+
next_node = ListNode()
34+
current.next = next_node
35+
current = current.next
36+
x = 0
37+
else:
38+
x += n.val
39+
40+
n = n.next
41+
42+
current.val = x
43+
return new_head
44+
```
45+
46+
- Both given test cases pass
47+
- Trying a new test case: `head = [0, 1, 0, 2, 0, 1, 2, 3, 4, 5, 0, 1, 0, 10, 1000, 1000, 1000, 0, 10, 10, 10, 10, 0]` (also passes)
48+
- Submitting...
49+
50+
![Screenshot 2024-07-03 at 10 51 14 PM](https://github.com/ContextLab/leetcode-solutions/assets/9030494/ce0a50a6-9a97-4a5f-aeb6-68928f49d372)
51+
52+
Solved!
53+
54+
55+

0 commit comments

Comments
 (0)