Let’s start with one of the classic Linked List problems:
Given a linked list, determine if it has a cycle in it.
You might have come up with the solutions like
-
Using the
hash table
-
Using
the two-pointer technique
.
Try to think it over by yourself before jumping to the more efficient two-pointer solution
i.e. using two pointers with different speed in a linked list:
a. If there is no cycle, the fast pointer will stop at the end of the linked list.
b. If there is a cycle, the fast pointer will eventually meet with the slow pointer.
So the only remaining problem is:
What should be the proper speed for the two pointers?