Skip to content

Commit 2bc2237

Browse files
add a second solution for 1171
1 parent d8c4ff5 commit 2bc2237

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/main/java/com/fishercoder/solutions/_1171.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,37 @@ private List<Integer> shrinkList(List<Integer> list) {
7272
return list;
7373
}
7474
}
75+
76+
public static class Solution2 {
77+
/**
78+
* credit: https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/discuss/366337/Java-Iterative-and-Recursive-solution
79+
* this post explains it all
80+
* key of the hashmap is the prefix sum of all the nodes we've gone so far
81+
* value of the hashmap is the corresponding linked list node
82+
*/
83+
public ListNode removeZeroSumSublists(ListNode head) {
84+
ListNode pre = new ListNode(-1);
85+
ListNode curr = pre;
86+
pre.next = head;
87+
Map<Integer, ListNode> map = new HashMap<>();
88+
int preSum = 0;
89+
while (curr != null) {
90+
preSum += curr.val;
91+
if (map.containsKey(preSum)) {
92+
curr = map.get(preSum).next;
93+
int key = preSum + curr.val;
94+
while (key != preSum) {
95+
map.remove(key);
96+
curr = curr.next;
97+
key += curr.val;
98+
}
99+
map.get(preSum).next = curr.next;
100+
} else {
101+
map.put(preSum, curr);
102+
}
103+
curr = curr.next;
104+
}
105+
return pre.next;
106+
}
107+
}
75108
}

src/test/java/com/fishercoder/_1171Test.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,24 @@
1010

1111
public class _1171Test {
1212
private static _1171.Solution1 solution1;
13+
private static _1171.Solution2 solution2;
1314

1415
@BeforeClass
1516
public static void setup() {
1617
solution1 = new _1171.Solution1();
18+
solution2 = new _1171.Solution2();
1719
}
1820

1921
@Test
2022
public void test1() {
2123
assertEquals(LinkedListUtils.contructLinkedList(new int[]{3, 1}), solution1.removeZeroSumSublists(LinkedListUtils.contructLinkedList(new int[]{1, 2, -3, 3, 1})));
24+
assertEquals(LinkedListUtils.contructLinkedList(new int[]{3, 1}), solution2.removeZeroSumSublists(LinkedListUtils.contructLinkedList(new int[]{1, 2, -3, 3, 1})));
2225
}
2326

2427
@Test
2528
public void test2() {
2629
assertEquals(LinkedListUtils.contructLinkedList(new int[]{1, 2, 4}), solution1.removeZeroSumSublists(LinkedListUtils.contructLinkedList(new int[]{1, 2, 3, -3, 4})));
30+
assertEquals(LinkedListUtils.contructLinkedList(new int[]{1, 2, 4}), solution2.removeZeroSumSublists(LinkedListUtils.contructLinkedList(new int[]{1, 2, 3, -3, 4})));
2731
}
2832

2933
@Test

0 commit comments

Comments
 (0)