1591. Loop Breaker

Medium3.5 points estimatedLinked ListTwo Pointers

A delivery route was meant to be a one-way chain of stops, but a faulty merge made some stop point back to an earlier one, forming a loop. Given the head of a singly linked list that may contain a cycle, write breakLoop(head). If the list has a cycle, find the stop where the loop begins, find the node whose next points to that stop, set that next to null, and return head. If there is no cycle, return head unchanged; an empty list gives null. Test inputs are objects with values and pos, where pos is the index the last node links back to, or -1 for no cycle. The list has 0 to 1000 nodes. Aim for O(n) time and O(1) extra space.

Example 1

Input:
head = {"values":[3,2,0,-4],"pos":1}
Output:
[3,2,0,-4]
Explanation:

The last node links back to index 1, so that link is cut.

Example 2

Input:
head = {"values":[1,2],"pos":0}
Output:
[1,2]
Explanation:

The loop starts at the head; node 2 is cut loose from it.

Example 3

Input:
head = {"values":[1,2,3],"pos":-1}
Output:
[1,2,3]
Explanation:

No cycle, so the list comes back unchanged.

Constraints

0 ≤ length ≤ 1000

pos = -1 or 0 ≤ pos < length

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…