| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | using LeetCode.Core.Models; |
| | | 13 | | |
| | | 14 | | namespace LeetCode.Algorithms.RemoveZeroSumConsecutiveNodesFromLinkedList; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public sealed class RemoveZeroSumConsecutiveNodesFromLinkedListDictionary : IRemoveZeroSumConsecutiveNodesFromLinkedList |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Time complexity - O(n) |
| | | 21 | | /// Space complexity - O(n) |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="head"></param> |
| | | 24 | | /// <returns></returns> |
| | | 25 | | public ListNode? RemoveZeroSumSublists(ListNode? head) |
| | 3 | 26 | | { |
| | 3 | 27 | | var dummyHead = new ListNode(0, head); |
| | | 28 | | |
| | 3 | 29 | | var prefixSumDictionary = new Dictionary<int, ListNode>(); |
| | | 30 | | |
| | 3 | 31 | | var prefixSum = 0; |
| | | 32 | | |
| | 42 | 33 | | for (var current = dummyHead; current != null; current = current.next) |
| | 18 | 34 | | { |
| | 18 | 35 | | prefixSum += current.val; |
| | 18 | 36 | | prefixSumDictionary[prefixSum] = current; |
| | 18 | 37 | | } |
| | | 38 | | |
| | 3 | 39 | | prefixSum = 0; |
| | | 40 | | |
| | 24 | 41 | | for (var current = dummyHead; current != null; current = current.next) |
| | 9 | 42 | | { |
| | 9 | 43 | | prefixSum += current.val; |
| | | 44 | | |
| | 9 | 45 | | if (prefixSumDictionary.TryGetValue(prefixSum, out var value)) |
| | 9 | 46 | | { |
| | 9 | 47 | | current.next = value.next; |
| | 9 | 48 | | } |
| | 9 | 49 | | } |
| | | 50 | | |
| | 3 | 51 | | return dummyHead.next; |
| | 3 | 52 | | } |
| | | 53 | | } |