Where does the cycle start?

The last node of a linked list may point back to an earlier node, which makes a cycle. Find where the cycle begins.

What to build

A program that finds the first node of the cycle, if there is one.

Requirements

  • pos is the position (from 0) of the node that the last node points to; pos = -1 means no cycle.
  • Print the value of the first node of the cycle, or none. All values are different.
  • Use Floyd's two pointers, not a set, so the extra memory is O(1) apart from the list.

Input

The first line has n and pos. The second line has the n values from head to tail.

Output

The value where the cycle starts, or none.

Constraints

1 ≤ n ≤ 10⁴.

Example

Input:

4 1
3 2 0 -4

Output:

2

Why it works

Fast and slow pointers meet inside the cycle. The distance from the head to the cycle start equals the distance from the meeting point onward to the cycle start (modulo the cycle length), so walking one pointer from the head and one from the meeting point at the same speed makes them meet at the start.

Examples

Example 1 · Input
4 1
3 2 0 -4
Expected output
2
Example 2 · Input
3 -1
1 2 3
Expected output
none

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Phase 1: move slow by 1 and fast by 2 until they meet; if fast reaches the end there is no cycle.

Hint 2

Phase 2: put one pointer back at the head and move both by 1; they meet at the first node of the cycle.

Hint 3

Build a list of node objects and link the last one to the node at position pos.

Solution

Show one correct solution (try it yourself first)
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None


n, pos = map(int, input().split())
values = input().split()
nodes = [Node(v) for v in values]
for i in range(n - 1):
    nodes[i].next = nodes[i + 1]
if pos != -1:
    nodes[-1].next = nodes[pos]
head = nodes[0]
slow = fast = head
meet = None
while fast and fast.next:
    slow = slow.next
    fast = fast.next.next
    if slow is fast:
        meet = slow
        break
if meet is None:
    print("none")
else:
    a, b = head, meet
    while a is not b:
        a = a.next
        b = b.next
    print(a.value)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Linked list patterns →