Skip to content

Commit

Permalink
Merge 4e57e22 into a09bb00
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz authored Jan 11, 2020
2 parents a09bb00 + 4e57e22 commit 81575af
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -413,4 +413,5 @@ problems from
* [Day 414](https://github.com/vaskoz/dailycodingproblem-go/issues/836)
* [Day 415](https://github.com/vaskoz/dailycodingproblem-go/issues/838)
* [Day 416](https://github.com/vaskoz/dailycodingproblem-go/issues/840)
* [Day 417](https://github.com/vaskoz/dailycodingproblem-go/issues/842)

35 changes: 35 additions & 0 deletions day417/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package day417

// LL is a linked list of integers.
type LL struct {
Value int
Next *LL
}

// RemoveConsecutiveSumZero removes all sublists that sum to zero.
// Runs in O(N^2) time and O(1) space.
func RemoveConsecutiveSumZero(head *LL) *LL {
fakeHead := &LL{0, head}

for start := fakeHead; start != nil; start = start.Next {
var sum int

var farthest *LL

var found bool

for next := start.Next; next != nil; next = next.Next {
sum += next.Value
if sum == 0 {
farthest = next.Next
found = true
}
}

if found {
start.Next = farthest
}
}

return fakeHead.Next
}
60 changes: 60 additions & 0 deletions day417/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package day417

import "testing"

// nolint
var testcases = []struct {
input, expected *LL
}{
{
&LL{3, &LL{4, &LL{-7, &LL{5, &LL{-6, &LL{6, nil}}}}}},
&LL{5, nil},
},
{
&LL{3, &LL{4, &LL{5, &LL{-12, nil}}}},
nil,
},
{
&LL{3, &LL{4, &LL{-7, &LL{5, &LL{-5, &LL{6, nil}}}}}},
&LL{6, nil},
},
{
&LL{3, &LL{4, &LL{-7, &LL{3, &LL{5, &LL{-6, &LL{6, &LL{-5, nil}}}}}}}},
&LL{3, nil},
},
{
&LL{1, &LL{1, &LL{2, &LL{3, &LL{4, &LL{5, &LL{6, &LL{-5, nil}}}}}}}},
&LL{1, &LL{1, &LL{2, &LL{3, &LL{4, &LL{5, &LL{6, &LL{-5, nil}}}}}}}},
},
}

func equal(a, b *LL) bool {
for a != nil && b != nil {
if a.Value != b.Value {
return false
}

a = a.Next
b = b.Next
}

return a == nil && b == nil
}

func TestRemoveConsecutiveSumZero(t *testing.T) {
t.Parallel()

for tcid, tc := range testcases {
if result := RemoveConsecutiveSumZero(tc.input); !equal(result, tc.expected) {
t.Errorf("TCID%d doesn't match", tcid)
}
}
}

func BenchmarkRemoveConsecutiveSumZero(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
RemoveConsecutiveSumZero(tc.input)
}
}
}

0 comments on commit 81575af

Please sign in to comment.