Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Linked List

Length of a Loop in a Linked List

Easy · Linked List · Asked at Amazon, Adobe, Qualcomm, TCS, Infosys

The tail of the list may link back to an earlier node, forming a loop. Print the number of nodes in the loop, or 0 if there is no loop.

Input

First line: n pos — pos is the 0-based index of the node the tail links back to, or -1 for no loop. Second line: the n node values.

Output

The length of the loop, or 0.

Constraints

Find a meeting point with slow and fast pointers (Floyd). Then keep one pointer still and move the other until it comes back — the number of steps is the loop length.

Example 1

Input

5 1
1 2 3 4 5

Output

4

Example 2

Input

3 -1
1 2 3

Output

0

Hints

  1. First decide whether there is a loop: slow moves 1 step, fast moves 2.
  2. If they meet, the meeting node is inside the loop.
  3. From there, walk around once and count the steps until you are back.

Approach

Floyd's algorithm: if fast reaches null there is no loop — print 0. Otherwise slow and fast meet at a node inside the loop. Keep one pointer there and move another one step at a time until it returns to the same node; the number of steps is the loop length. This uses O(1) memory, unlike storing visited nodes.

Complexity: O(n) time · O(1) extra space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

struct Node {
    long long val;
    Node *next = nullptr;
    Node(long long v) : val(v) {}
};

int main() {
    int n, pos;
    cin >> n >> pos;
    vector<Node *> nodes(n);
    for (int i = 0; i < n; i++) {
        long long x;
        cin >> x;
        nodes[i] = new Node(x);
        if (i) nodes[i - 1]->next = nodes[i];
    }
    if (pos >= 0) nodes[n - 1]->next = nodes[pos];
    Node *slow = nodes[0], *fast = nodes[0];
    while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast) {
            int len = 1;
            for (Node *p = slow->next; p != slow; p = p->next) len++;
            cout << len << "\n";
            return 0;
        }
    }
    cout << 0 << "\n";
    return 0;
}

Python solution

import sys


class Node:
    def __init__(self, val):
        self.val, self.next = val, None


data = list(map(int, sys.stdin.read().split()))
n, pos = data[0], data[1]
nodes = [Node(v) for v in data[2 : 2 + n]]
for i in range(n - 1):
    nodes[i].next = nodes[i + 1]
if pos >= 0:
    nodes[-1].next = nodes[pos]
slow = fast = nodes[0]
answer = 0
while fast and fast.next:
    slow = slow.next
    fast = fast.next.next
    if slow is fast:
        answer, p = 1, slow.next
        while p is not slow:
            answer += 1
            p = p.next
        break
print(answer)

Java solution

import java.io.*;

public class Main {
    static class Node {
        long val;
        Node next;
        Node(long v) { val = v; }
    }

    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        in.nextToken();
        int pos = (int) in.nval;
        Node[] nodes = new Node[n];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            nodes[i] = new Node((long) in.nval);
            if (i > 0) nodes[i - 1].next = nodes[i];
        }
        if (pos >= 0) nodes[n - 1].next = nodes[pos];
        Node slow = nodes[0], fast = nodes[0];
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                int len = 1;
                for (Node p = slow.next; p != slow; p = p.next) len++;
                System.out.println(len);
                return;
            }
        }
        System.out.println(0);
    }
}

Solve Length of a Loop in a Linked List online · All practice problems