LeetCode #141 Linked List Cycle
Problem
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Solution
Here we will use two pointers walker
and runner
for detecting cycle. Make runner
run two nodes in a iteration and walker
go only one node. By doing so, they will finally meet if there is a cycle in this linked list.
Complexity
There are two cases for analytics:
- If there is no cycle in this linked list, it’s obvious that
runner
will take O(n/2) time to run through this linked list whichn
denotes to amount of nodes in this linked list. - If there exists a cycle in this linked list, they will meet each other at a node, say
x
, andx
represents thex
-th node in this list. Let’s assume the position of cycle start is aty
-th node and the length of cycle ism
. We know after they meet each other,runner
has already run2x
nodes, which is equal toy + m + (x — y)
(length to cycle start + length of cycle + nodes to meetwalker
). So we have2x = y + m + (x — y)
, and it can conduct tox = m
. Therefore, we knowrunner
has to run O(m) time for catching upwalker
totally.
Because n
is the counts of nodes in linked and m
is only the length of cycle, m
will definitely be less than n
. Therefore, the time complexity will be O(n).
It’s trivial that space complexity of this approach is only O(1).