|
U
Pro60. Detect Cycle in Linked List
Easy
Problem Description
Given a linked list representation where the tail connects back to the 0-based node index pos (or -1 if no cycle), determine whether a cycle exists using Floyd's cycle-finding algorithm.
Input Format
- •Line 1: Two space-separated integers N and pos (1≤N≤105, −1≤pos<N).
- •Line 2: N space-separated integers.
Output Format
Print true if a cycle exists, else false.
Example 1:
Input:
4 1 3 2 0 -4
Output:
true
Explanation: Tail connects back to node at index 1; cycle exists.
Example 2:
Input:
2 0 1 2
Output:
true
Explanation: Tail connects to index 0; cycle exists.
Example 3:
Input:
1 -1 1
Output:
false
Explanation: No cycle (pos = -1).
Constraints:
Standard integer bounds: 32-bit signed integer or input range [1, 10^5].Time complexity target: O(N) or O(N log N) where applicable.Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online
Code
|Loading Code Editor...
SavedLn 1, Col 1
param_1 =
param_2 =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit