| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 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 class RemoveZeroSumConsecutiveNodesFromLinkedListBruteForce : IRemoveZeroSumConsecutiveNodesFromLinkedList |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n^3) |
| | 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 | | if (head == null) |
| 0 | 28 | | { |
| 0 | 29 | | return null; |
| | 30 | | } |
| | 31 | |
|
| 3 | 32 | | var values = new List<int>(); |
| | 33 | |
|
| 18 | 34 | | while (head != null) |
| 15 | 35 | | { |
| 15 | 36 | | values.Add(head.val); |
| | 37 | |
|
| 15 | 38 | | head = head.next; |
| 15 | 39 | | } |
| | 40 | |
|
| 3 | 41 | | var i = 0; |
| | 42 | |
|
| 18 | 43 | | while (i < values.Count) |
| 15 | 44 | | { |
| 82 | 45 | | for (var j = i; j >= 0; j--) |
| 30 | 46 | | { |
| 30 | 47 | | var sum = 0; |
| | 48 | |
|
| 158 | 49 | | for (var k = j; k <= i; k++) |
| 49 | 50 | | { |
| 49 | 51 | | sum += values[k]; |
| 49 | 52 | | } |
| | 53 | |
|
| 30 | 54 | | if (sum != 0) |
| 26 | 55 | | { |
| 26 | 56 | | continue; |
| | 57 | | } |
| | 58 | |
|
| 4 | 59 | | values.RemoveRange(j, i - j + 1); |
| | 60 | |
|
| 4 | 61 | | i -= i - j + 1; |
| | 62 | |
|
| 4 | 63 | | break; |
| | 64 | | } |
| | 65 | |
|
| 15 | 66 | | i++; |
| 15 | 67 | | } |
| | 68 | |
|
| 3 | 69 | | if (values.Count == 0) |
| 0 | 70 | | { |
| 0 | 71 | | return null; |
| | 72 | | } |
| | 73 | |
|
| 3 | 74 | | var dummyHead = new ListNode(); |
| | 75 | |
|
| 3 | 76 | | var current = dummyHead; |
| | 77 | |
|
| 21 | 78 | | foreach (var value in values) |
| 6 | 79 | | { |
| 6 | 80 | | current.next = new ListNode(value); |
| 6 | 81 | | current = current.next; |
| 6 | 82 | | } |
| | 83 | |
|
| 3 | 84 | | return dummyHead.next; |
| 3 | 85 | | } |
| | 86 | | } |