Q: How do you detect a cycle in a linked list?
A: To detect a cycle in a linked list, you can use Floyd's Cycle Detection Algorithm, also known as the Tortoise and Hare Algorithm. In this approach, two pointers (slow and fast) traverse the list. The slow pointer moves one step at a time, while the fast pointer moves two steps. If the linked list contains a cycle, the two pointers will eventually meet; otherwise, the fast pointer will reach the end of the list.
This algorithm runs in O(n) time complexity and uses O(1) space.
The above is the detailed content of Most Asked DSA Interview Questions. For more information, please follow other related articles on the PHP Chinese website!