-
Notifications
You must be signed in to change notification settings - Fork 0
/
cycle_start_test.go
126 lines (103 loc) · 2.13 KB
/
cycle_start_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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/*
Problem:
- Given the head of a singly linked list, write a function to find the
starting node of the cycle.
Approach:
- Similar to finding a cycle in a linked list problem, can also determine
the start of its cycle and calculate length k of the cycle.
- Have one pointer at the beginning and one at kth node of the linked list.
- Move both of them until they meet at the start.of the cycle.
Cost:
- O(n) time, O(1) space.
*/
package gtci
import (
"testing"
"github.com/pcaruana/algo/common"
)
func TestFindCycleStart(t *testing.T) {
t1 := common.NewListNode(1)
t1.AddNext(2)
t1.AddNext(3)
t1.AddNext(4)
t1.AddNext(5)
t1.AddNext(6)
t1.Next.Next.Next.Next.Next.Next = t1.Next.Next
t2 := common.NewListNode(1)
t2.AddNext(2)
t2.AddNext(3)
t2.AddNext(4)
t2.AddNext(5)
t2.AddNext(6)
t2.Next.Next.Next.Next.Next.Next = t2.Next.Next.Next
t3 := common.NewListNode(1)
t3.AddNext(2)
t3.AddNext(3)
t3.AddNext(4)
t3.AddNext(5)
t3.AddNext(6)
t3.Next.Next.Next.Next.Next.Next = t3
t4 := common.NewListNode(1)
t4.AddNext(2)
t4.AddNext(3)
t4.AddNext(4)
t4.AddNext(5)
t4.AddNext(6)
tests := []struct {
in *common.ListNode
expected int
}{
{t1, 3},
{t2, 4},
{t3, 1},
{t4, 1},
}
for _, tt := range tests {
common.Equal(
t,
tt.expected,
findCycleStart(tt.in),
)
}
}
func findCycleStart(head *common.ListNode) int {
length := 0
slow, fast := head, head
for fast != nil && fast.Next != nil {
fast = fast.Next.Next
slow = slow.Next
if slow == fast {
length = cycleLength(slow)
break
}
}
start := findStart(head, length)
return start.Value
}
// cycleLength loops around the cycle and calculate its length.
func cycleLength(head *common.ListNode) int {
length := 0
current := head
for true {
current = current.Next
length++
if current == head {
break
}
}
return length
}
func findStart(head *common.ListNode, k int) *common.ListNode {
slow, fast := head, head
// move the fast pointer k distance ahead.
for k > 0 {
fast = fast.Next
k--
}
// increment both pointers until they meet at the start.
for slow != fast {
slow = slow.Next
fast = fast.Next
}
return slow
}