Detecting a loop in constant space — Aptitude Question
Detecting a loop in constant space: Which technique detects a loop in a singly linked list using only O(1) extra… Answer and worked solution on CodeKairo.
- Topic: Data Structures & Algorithms
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
Which technique detects a loop in a singly linked list using only O(1) extra space?
Options
- Floyd's cycle-finding algorithm with a slow and a fast pointer
- Kadane's algorithm
- Recording every visited node in a hash set
- Sorting the node addresses and looking for a repeat
Show the answer and the worked solution
Correct answer: A. Floyd's cycle-finding algorithm with a slow and a fast pointer
Worked solution
- A hash set of visited nodes does detect a loop, but it grows to O(n) space.
- Sorting addresses needs the addresses collected first, which is also O(n) space, and Kadane's algorithm solves a maximum-subarray problem entirely unrelated to lists.
- Floyd's cycle-finding algorithm with a slow and a fast pointer advances one pointer one node at a time and the other two at a time; inside a loop the fast pointer gains one node per step until the two meet, and only two pointers are ever stored.
Answer: Floyd's cycle-finding algorithm with a slow and a fast pointer.
The idea
The tortoise-and-hare test is the standard O(1)-space loop detector, and the meeting point also lets you find where the loop starts and how long it is.
Shortcut. O(1) space rules out anything that stores nodes, the hash set and the sorted addresses, and Kadane's algorithm solves maximum subarray, which leaves the two-pointer method.
Common trap. "Recording every visited node in a hash set" does detect a loop and is the usual first idea, but it needs O(n) space.
All Data Structures & Algorithms questions · placement mock tests