Linked List Cycle

Given a linked list with potentially a loop, determine whether the linked list from the first node contains a cycle in it. For bonus points, do this with constant space.

Parameters

  • nodes: The first node of a linked list with potentially a loop.

Result

  • Whether there is a loop contained in the linked list.

Examples

Example 1

Input:

Output:

true

Example 2

Input:

Output:

false

Constraints

  • 1 <= len(nodes) <= 10^5

Try it yourself

Solution

If a linked list has no loop, then when we iterate through the list, we will eventually reach the end of the list, at which point we can simply return. However, the challenge is figuring out how to terminate the program if it finds a loop. Otherwise the program would go on forever.

A simple solution would be to use a set to store the information. We store all the nodes we have been through and check if we have been there each time we move. However, a set is not constant memory, and there might be issues with hashing and whatnot. Clearly there is a better way.

Introducing Floyd's Cycle Finding Algorithm, also known as the Tortoise and Hare Algorithm. The idea is to have two pointers, the fast pointer (or "hare") moves at double speed of the slow pointer (or "tortoise"). Each cycle, the tortoise moves once and the hare moves twice. The idea is that since the cycle must have integer size, when the tortoise and the hare are both in the cycle, their distance difference must also be an integer. Then, each cycle, because of their speed difference, the distance between them constantly reduces until they meet, in which case we know there is a cycle. However, if there is no cycle, they will never meet because the speed of the hare is always faster.

Time Complexity: O(n)

Technically O(n/2) but again we factor out the constant and we are left with linear time. Worst case we have, O(2n) as the small pointer moves around the entire array once. Either way we have O(n) time complexity.

Space Complexity: O(1)

This is a graphics that explains the idea:

Below is an implementation.

1class Node:
2    def __init__(self, val, next=None):
3        self.val = val
4        self.next = next
5
6def node_next(node):
7    return node.next or node
8
9def has_cycle(nodes: Node) -> bool:
10    tortoise = node_next(nodes)
11    hare = node_next(node_next(nodes))
12    while tortoise != hare and hare.next is not None:
13        tortoise = node_next(tortoise)
14        hare = node_next(node_next(hare))
15    return hare.next is not None
16
17if __name__ == "__main__":
18    raw_input = [int(x) for x in input().split()]
19    nodes_list = []
20    for i in range(len(raw_input)):
21        nodes_list.append(Node(i))
22    for i, entry in enumerate(raw_input):
23        if entry != -1:
24            nodes_list[i].next = nodes_list[entry]
25    nodes = nodes_list[0]
26    res = has_cycle(nodes)
27    print("true" if res else "false")
28
1import java.util.ArrayList;
2import java.util.Arrays;
3import java.util.List;
4import java.util.Scanner;
5import java.util.stream.Collectors;
6
7class Solution {
8    public static class Node<T> {
9        public T val;
10        public Node<T> next;
11
12        public Node(T val) {
13            this(val, null);
14        }
15
16        public Node(T val, Node<T> next) {
17            this.val = val;
18            this.next = next;
19        }
20    }
21
22    public static Node<Integer> nextNode(Node<Integer> node) {
23        if (node.next == null) {
24            return node;
25        }
26        return node.next;
27    }
28
29    public static boolean hasCycle(Node<Integer> nodes) {
30        Node<Integer> tortoise = nextNode(nodes);
31        Node<Integer> hare = nextNode(nextNode(nodes));
32        while (tortoise != hare && hare.next != null) {
33            tortoise = nextNode(tortoise);
34            hare = nextNode(nextNode(hare));
35        }
36        return hare.next != null;
37    }
38
39    public static List<String> splitWords(String s) {
40        return s.isEmpty() ? List.of() : Arrays.asList(s.split(" "));
41    }
42
43    public static void main(String[] args) {
44        Scanner scanner = new Scanner(System.in);
45        List<Integer> rawInput = splitWords(scanner.nextLine()).stream().map(Integer::parseInt).collect(Collectors.toList());
46        ArrayList<Node<Integer>> nodesList = new ArrayList<>();
47        for (int i = 0; i < rawInput.size(); i++) {
48            nodesList.add(new Node<Integer>(i));
49        }
50        for (int i = 0; i < rawInput.size(); i++) {
51            if (rawInput.get(i) != -1) {
52                nodesList.get(i).next = nodesList.get(rawInput.get(i));
53            }
54        }
55        Node<Integer> nodes = nodesList.get(0);
56        scanner.close();
57        boolean res = hasCycle(nodes);
58        System.out.println(res);
59    }
60}
61
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5class Solution
6{
7    public class Node<T>
8    {
9        public T val;
10        public Node<T> next;
11
12        public Node(T val)
13        {
14            this.val = val;
15        }
16
17        public Node(T val, Node<T> next)
18        {
19            this.val = val;
20            this.next = next;
21        }
22    }
23
24    public static Node<int> NextNode(Node<int> node)
25    {
26        if (node.next == null)
27        {
28            return node;
29        }
30        return node.next;
31    }
32
33    public static bool HasCycle(Node<int> nodes)
34    {
35        Node<int> tortoise = NextNode(nodes);
36        Node<int> hare = NextNode(NextNode(nodes));
37        while (tortoise != hare && hare.next != null)
38        {
39            tortoise = NextNode(tortoise);
40            hare = NextNode(NextNode(hare));
41        }
42        return hare.next != null;
43    }
44
45    public static List<string> SplitWords(string s)
46    {
47        return string.IsNullOrEmpty(s) ? new List<string>() : s.Trim().Split(' ').ToList();
48    }
49
50    public static void Main()
51    {
52        List<int> rawInput = SplitWords(Console.ReadLine()).Select(int.Parse).ToList();
53        List<Node<int>> nodesList = new List<Node<int>>();
54        for (int i = 0; i < rawInput.Count; i++)
55        {
56            nodesList.Add(new Node<int>(i));
57        }
58        for (int i = 0; i < rawInput.Count; i++)
59        {
60            if (rawInput[i] != -1)
61            {
62                nodesList[i].next = nodesList[rawInput[i]];
63            }
64        }
65        Node<int> nodes = nodesList[0];
66        bool res = HasCycle(nodes);
67        Console.WriteLine(res ? "true" : "false");
68    }
69}
70
1"use strict";
2
3class Node {
4    constructor(val, next = null) {
5        this.val = val;
6        this.next = next;
7    }
8}
9
10function nextNode(node) {
11    if (node.next === null) return node;
12    return node.next;
13}
14
15function hasCycle(nodes) {
16    let tortoise = nextNode(nodes);
17    let hare = nextNode(nextNode(nodes));
18    while (tortoise !== hare && hare.next !== null) {
19        tortoise = nextNode(tortoise);
20        hare = nextNode(nextNode(hare));
21    }
22    return hare.next !== null;
23}
24
25function splitWords(s) {
26    return s === "" ? [] : s.split(" ");
27}
28
29function* main() {
30    const rawInput = splitWords(yield).map((v) => parseInt(v));
31    const nodesList = [];
32    for (let i = 0; i < rawInput.length; i++) {
33        nodesList.push(new Node(i));
34    }
35    for (let i = 0; i < rawInput.length; i++) {
36        if (rawInput[i] !== -1) {
37            nodesList[i].next = nodesList[rawInput[i]];
38        }
39    }
40    const nodes = nodesList[0];
41    const res = hasCycle(nodes);
42    console.log(res);
43}
44
45class EOFError extends Error {}
46{
47    const gen = main();
48    const next = (line) => gen.next(line).done && process.exit();
49    let buf = "";
50    next();
51    process.stdin.setEncoding("utf8");
52    process.stdin.on("data", (data) => {
53        const lines = (buf + data).split("\n");
54        buf = lines.pop();
55        lines.forEach(next);
56    });
57    process.stdin.on("end", () => {
58        buf && next(buf);
59        gen.throw(new EOFError());
60    });
61}
62
1#include <algorithm>
2#include <iostream>
3#include <iterator>
4#include <sstream>
5#include <string>
6#include <vector>
7
8template<typename T>
9struct Node {
10    T val;
11    Node<T>* next;
12
13    explicit Node(T val, Node<T>* next = nullptr)
14        : val{val}, next{next} {}
15
16    ~Node() {
17        delete next;
18    }
19};
20
21Node<int>* next_node(Node<int>* node) {
22    if (node->next == nullptr) {
23        return node;
24    }
25    return node->next;
26}
27
28bool has_cycle(Node<int>* nodes) {
29    Node<int>* tortoise = next_node(nodes);
30    Node<int>* hare = next_node(next_node(nodes));
31    while (tortoise != hare && hare->next != nullptr) {
32        tortoise = next_node(tortoise);
33        hare = next_node(next_node(hare));
34    }
35    return hare->next != nullptr;
36}
37
38template<typename T>
39std::vector<T> get_words() {
40    std::string line;
41    std::getline(std::cin, line);
42    std::istringstream ss{line};
43    ss >> std::boolalpha;
44    std::vector<T> v;
45    std::copy(std::istream_iterator<T>{ss}, std::istream_iterator<T>{}, std::back_inserter(v));
46    return v;
47}
48
49int main() {
50    std::vector<int> rawInput = get_words<int>();
51    std::vector<Node<int>*> nodeList;
52    for (int i = 0; i < rawInput.size(); i++) {
53        nodeList.push_back(new Node<int>(i));
54    }
55    for (int i = 0; i < rawInput.size(); i++) {
56        if (rawInput[i] != -1) {
57            nodeList[i]->next = nodeList[rawInput[i]];
58        }
59    }
60    Node<int>* nodes = nodeList[0];
61    bool res = has_cycle(nodes);
62    std::cout << std::boolalpha << res << '\n';
63}
64

Invest in Yourself

Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.

Go Pro