06.03.2024
141. Linked List Cycle easy
blog post
Join me on Telegram
https://t.me/leetcode_daily_unstoppable/530
Problem TLDR
Detect cycle #easy
Intuition
Use two pointers, fast and slow, they will meet sometime.
Approach
No Rust in the templates provided, sorry.
Complexity
Time complexity:
O(n)Space complexity:
O(1)
Code
fun hasCycle(h: ListNode?, f: ListNode? = h?.next): Boolean =
f != null && (h == f || hasCycle(h?.next, f?.next?.next))
bool hasCycle(ListNode *s) {
auto f = s;
while (f && f->next) {
s = s->next; f = f->next->next;
if (s == f) return true;
}
return false;
}