Detect Cycle in Linked List
Practice this coding question on Coding Gurukul.
Problem statement
A device follows next pointers through a chain of maintenance records. A damaged final pointer may send it back to an earlier record, causing it to loop forever. The diagnostic must detect this without modifying the records. Your task Build a list of n nodes in input order. If pos is not -1, link the final node back to node pos. Determine whether the resulting linked list contains a cycle. Important details Positions are zero-based. Repeated values alone do not indicate a cycle; only revisiting the same node does. Use Floyd's slow/fast pointer method with O(1) extra space. The pos field describes the test fixture and must not replace traversal in your detection routine. Worked example For values [4, 8, 2] and pos = 1, the last node points back to the node holding 8. Traversal repeats 8, 2, 8, 2, so the answer is true.
Input format
First line: n pos. Next line: n values.
Output format
Print true if the condition holds, otherwise false.
Constraints
0 <= n <= 10000; -100000 <= values <= 100000; pos = -1 or 0 <= pos < n; for n = 0, pos = -1.
Sample input
3 1 4 8 2
Sample output
true
Sign in to run or submit a solution in C++, Java or Python.