HomeGorakh Raj Joshi

Linked List Cycle

Time Complexity O(n)/Space Complexity O(1)

  • #LeetCode
  • #FastSlowPointer

https://leetcode.com/problems/linked-list-cycle

class Node {
  constructor(value, next = null) {
    this.value = value;
    this.next = next;
  }
}

function hasCycle(head) {
  let slow = head;
  let fast = head;

  while (fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow === fast) {
      return true;
    }
  }
  return false;
}

const head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(6);
head.next.next.next.next.next.next = head.next.next;

hasCycle(head);

Gorakh Raj Joshi

Senior Fullstack Engineer: Specializing in System Design and Architecture, Accessibility, and Frontend Interface Design

LinkedIn

GitHub

Email

All rights reserved © Gorakh Raj Joshi 2024