Skip to content

Commit

Permalink
Merge pull request #623 from vaskoz/day305
Browse files Browse the repository at this point in the history
Day305
  • Loading branch information
vaskoz committed Jun 24, 2019
2 parents c051549 + 9ba534b commit 66e1049
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,3 +311,4 @@ problems from
* [Day 302](https://github.com/vaskoz/dailycodingproblem-go/issues/615)
* [Day 303](https://github.com/vaskoz/dailycodingproblem-go/issues/616)
* [Day 304](https://github.com/vaskoz/dailycodingproblem-go/issues/618)
* [Day 305](https://github.com/vaskoz/dailycodingproblem-go/issues/622)
29 changes: 29 additions & 0 deletions day305/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package day305

// 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
}
57 changes: 57 additions & 0 deletions day305/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package day305

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 66e1049

Please sign in to comment.