-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedListCycle.ts
65 lines (53 loc) · 1.85 KB
/
linkedListCycle.ts
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
/* Question: write a fn that determines if a linked list is cyclic */
/* Implementation using extra space -> Time: O(N) | Space: O(N) */
import { LinkedListNode } from "./data-structures/singly_linked_list.ts";
function isLinkedListCyclic(head?: LinkedListNode): boolean {
const visited = new Set<LinkedListNode>();
for (let node = head; node !== undefined; node = node?.next) {
if (visited.has(node)) return true;
visited.add(node);
}
return false;
}
/* Implementation using Floyd's algorithm -> Time: O(N) | Space: O(1) */
function isLLCyclic(head?: LinkedListNode): boolean {
let slow = head, fast = head?.next;
while (slow && fast) {
if (slow === fast) return true;
slow = slow.next;
fast = fast.next?.next;
}
return false;
}
/* Tests */
import { assertEquals } from "./deps.ts";
Deno.test("undefined head node", () => {
assertEquals(isLLCyclic(undefined), false);
assertEquals(isLinkedListCyclic(undefined), false);
});
Deno.test("single head node w/o cycle", () => {
const node = new LinkedListNode(1);
assertEquals(isLLCyclic(node), false);
assertEquals(isLinkedListCyclic(node), false);
});
Deno.test("single head node w/ cycle", () => {
const node = new LinkedListNode(1);
node.next = node;
assertEquals(isLLCyclic(node), true);
assertEquals(isLinkedListCyclic(node), true);
});
Deno.test("multiple nodes w/o cycle", () => {
const node = new LinkedListNode(1);
node.next = new LinkedListNode(2);
node.next.next = new LinkedListNode(3);
assertEquals(isLLCyclic(node), false);
assertEquals(isLinkedListCyclic(node), false);
});
Deno.test("multiple nodes w/ cycle", () => {
const node = new LinkedListNode(1);
node.next = new LinkedListNode(2);
node.next.next = new LinkedListNode(3);
node.next.next.next = node;
assertEquals(isLLCyclic(node), true);
assertEquals(isLinkedListCyclic(node), true);
});