Fast and slow pointer technique

The fast and slow pointer technique (also known as the tortoise and hare algorithm) uses two pointers to determine traits about directional data structures. This can be an array, a singly-linked list, or a graph. It is often applied to determine if there are any cycles in the data structure and is therefore also known as Floyd’s Cycle Detection Algorithm.

Slow pointer and fast pointer are simply the names given to two pointer variables. The only difference is that the slow pointer travels the linked list one node at a time where as a fast pointer travels the linked list two nodes at a time. Think of a tortoise and a hare running on a track. The faster-running hare will catch up with the tortoise if the track is like a loop.

Finding a cycle in a linked list:

  var hasCycle = function (head) {
    if (!head) return false;

    let fast = head;
    let slow = head;

    while (slow) {
      slow = slow.next;
      fast = fast?.next?.next;

      if (slow === fast) return true;
    }

    return false;
  };