409. Detect and Remove Loop — All Edge Cases

HardLinked ListFloyd's Cycle DetectionTwo PointersLinked List

Given a linked list that may contain a loop, detect and remove the loop so the list becomes a proper linear list, then return the list as an array in node order. The input is the list values plus pos, the 0-based index the tail connects to (pos = -1 means no loop). After removal the list is the original linear sequence. Input: '[list], pos'.

Input: '[list], pos'.

Output: Array — the linearized list.

Examples

Example 1
Input: [1,2,3,4,5], 1
Output: [1,2,3,4,5]
Explanation: Loop removed; linear order remains.
Example 2
Input: [1,2,3,4], 0
Output: [1,2,3,4]
Explanation: Whole-list loop removed.
Example 3
Input: [1], -1
Output: [1]
Explanation: No loop.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →