Home > Reflections | โฎ๏ธ โญ๏ธ
2024-08-07 | ๐ Launch | ๐ Cycle | ๐ก Solve

๐ง Education
๐ Coding Practice
141.ย Linked List Cycle
Givenย
head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following theยnextย pointer. Internally,ยposย is used to denote the index of the node thatย tailโsยnextย pointer is connected to.ย Note thatยposย is not passed as a parameter.
Returnยtrueย if there is a cycle in the linked list. Otherwise, returnยfalse.
๐ช Reflections
- This was a good warm up for my upcoming interview, later today
- No bugs, optimal solution, correct submission on first attempt in under 14 minutes is pretty good!
โจ๏ธ My Solution
/* Deterimine if there is a cycle in a linked list
- Easy: collect nodes in a set and check if each new node exists in the set
- Note: O(N) extra memory usage
- Old PhD Thesis method, turned ubiquitous interview question: send out multiple cursors at different paces and return if they're ever at the same node
- O(1) extra memory usage
Both methods have O(N) run-time complexity
[2:24] Done planning
[6:34] Done with initial implementation
[9:18] Done with test
[13:25] Successful submission
*/
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function hasCycle(head: ListNode | null): boolean { // null; 1,2,3,1
if (!head || !head.next) return false // F
for (let c1 = head, c2 = head.next; c2.next && c2.next.next; c1 = c1.next, c2 = c2.next) {
// c1=2 c2=1; c1=1 c2=2
if (c1 === c2) return true
c2 = c2.next // c2=2; c2=3
if (c1 === c2) return true // T
}
return false
};