141. Linked List Cycle Leetcode Solution

Linked List Cycle Leetcode Problem :

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

jump game leetcode

Linked List Cycle Leetcode Solution :

Constraints :

  • The number of the nodes in the list is in the range [0, 104].
  • -105 <= Node.val <= 105
  • pos is -1 or a valid index in the linked-list.

Example 1:

  • Input: head = [1,2], pos = 0
  • Output: true

Example 2:

  • Input: head = [1], pos = -1
  • Output: false

Intuition :

Use a Floyd’s Tortoise and Hare algorithm to detect a cycle in a linked list and find the node where the cycle starts.

Approach :

Use Floyd’s Tortoise and Hare algorithm. it is a widely used algorithm for detecting cycles in a linked list
1 – Initialize two pointers, slow and fast, both pointing to the head of the linked list.

2 – Move the slow one step at a time, and the fast two steps at a time. This simulates a slow and fast movement through the list.

3 – If there is no cycle in the list, the ha fast will reach the end of the list, and you can stop the algorithm.

4 – If there is a cycle in the list, the fast will eventually catch up to the slow because it’s moving twice as fast. When this happens, you have detected a cycle.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription