Skip to content

Commit

Permalink
Merge 545b577 into cb75bd5
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Dec 23, 2019
2 parents cb75bd5 + 545b577 commit 7bb9e80
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -390,4 +390,5 @@ problems from
* [Day 395](https://github.com/vaskoz/dailycodingproblem-go/issues/793)
* [Day 396](https://github.com/vaskoz/dailycodingproblem-go/issues/795)
* [Day 397](https://github.com/vaskoz/dailycodingproblem-go/issues/797)
* [Day 398](https://github.com/vaskoz/dailycodingproblem-go/issues/799)

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

// SinglyLL is a singly linked list of interface{} type.
type SinglyLL struct {
Value interface{}
Next *SinglyLL
}

// RemoveKthFromEnd removes the k-th node from the
// end of the list and return the head of the list.
// Runs in O(N) time and O(1) space.
func RemoveKthFromEnd(head *SinglyLL, kth int) *SinglyLL {
headPtr := &SinglyLL{Value: nil, Next: head}
front := headPtr
follower := headPtr

for i := 0; i <= kth; i++ {
if front == nil {
panic("less than k elements in list")
}

front = front.Next
}

for ; front != nil; front = front.Next {
follower = follower.Next
}

follower.Next = follower.Next.Next

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

import "testing"

// nolint
var testcases = []struct {
head *SinglyLL
kth int
expected *SinglyLL
}{
{
&SinglyLL{1, &SinglyLL{2, &SinglyLL{3, &SinglyLL{4, &SinglyLL{5, nil}}}}},
2,
&SinglyLL{1, &SinglyLL{2, &SinglyLL{3, &SinglyLL{5, nil}}}},
},
{
&SinglyLL{1, &SinglyLL{2, &SinglyLL{3, &SinglyLL{4, &SinglyLL{5, nil}}}}},
5,
&SinglyLL{2, &SinglyLL{3, &SinglyLL{4, &SinglyLL{5, nil}}}},
},
}

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

for tcid, tc := range testcases {
if res := RemoveKthFromEnd(tc.head, tc.kth); !equal(res, tc.expected) {
t.Errorf("TCID%d singly linked lists do not match", tcid)
}
}
}

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

defer func() {
if err := recover(); err == nil {
t.Errorf("Expected a panic when k is larger than length")
}
}()

head := &SinglyLL{1, &SinglyLL{2, &SinglyLL{3, &SinglyLL{4, &SinglyLL{5, nil}}}}}
RemoveKthFromEnd(head, 6)
}

func BenchmarkRemoveKthFromEnd(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
RemoveKthFromEnd(tc.head, tc.kth)
}
}
}

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

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

0 comments on commit 7bb9e80

Please sign in to comment.