-
Notifications
You must be signed in to change notification settings - Fork 376
/
kth_to_last_test.go
92 lines (74 loc) · 1.7 KB
/
kth_to_last_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
Problem:
- Find the kth to last node in a linked list.
Example:
- Input: list = 1 -> 2 -> 3 -> 4 -> 5 -> 6, k = 2
Output: 5, because 5 is the 2nd to the last node (6)
Approach:
- Use two pointers such that one starts at the beginning and the other one
starts at k distance apart.
- Walk both at the same speed toward the end.
- When one hits the tail, the other one is on the target node.
Solution:
- Start both nodes, a left one and a right one, at the beginning.
- Move the right one to the kth node.
- Move both of them until the right one hits the end.
- Return the left one.
Cost:
- O(n) time and O(1) space.
*/
package interviewcake
import (
"testing"
"github.com/hoanhan101/algo/common"
)
func TestKthToLast(t *testing.T) {
// define tests input.
t1 := common.NewListNode(1)
t2 := common.NewListNode(1)
t2.AddNext(2)
t3 := common.NewListNode(1)
t3.AddNext(2)
t3.AddNext(3)
t4 := common.NewListNode(1)
for i := 2; i <= 6; i++ {
t4.AddNext(i)
}
// define tests output.
tests := []struct {
in1 *common.ListNode
in2 int
expected int
}{
{t1, 1, 1},
{t2, 1, 2},
{t2, 2, 1},
{t3, 1, 3},
{t3, 2, 2},
{t3, 3, 1},
{t4, 1, 6},
{t4, 2, 5},
{t4, 3, 4},
{t4, 4, 3},
{t4, 5, 2},
{t4, 6, 1},
}
for _, tt := range tests {
node := kthToLast(tt.in1, tt.in2)
common.Equal(t, tt.expected, node.Value)
}
}
func kthToLast(node *common.ListNode, k int) *common.ListNode {
// start both node in the beginning.
left, right := node, node
// move the right one to the kth node.
for i := 0; i < k-1; i++ {
right = right.Next
}
// move both pointers until the right one hits the end.
for right.Next != nil {
left = left.Next
right = right.Next
}
return left
}