Two slow and one fast pointer

class Solution {
ListNode *detectCycle(ListNode *head) {
if (head == nullptr)return nullptr;
ListNode* slow1 = head;
ListNode* slow2 = head;
ListNode* fast = head;

while (fast -> next != nullptr && fast -> next -> next!=nullptr){
fast = fast -> next -> next; slow1 = slow1 -> next;
if (slow1 == fast){//slow and fast meeting point B found.
while (slow1 != slow2)
slow1 = slow1 -> next, slow2 = slow2 -> next;
return slow1;
return nullptr;
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:return head
slow1, slow2, fast = [head]*3
while and
fast, slow1 =,
if slow1 == fast:
while slow1 != slow2:
slow1, slow2 =,
return slow1




Data Scientist/MLE/SWE @takemobi

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Rails Database Migrations with No Down Time using Gh-ost

Sia Community Update — July 2018

Skynet Content Leaderboard

Egg Catcher!

Go: Memory Management and Memory Sweep

Airline Reservation System in Java

General Assembly Singapore Review — Web Development Immersive

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jimmy Shen

Jimmy Shen

Data Scientist/MLE/SWE @takemobi

More from Medium

Machine Learning for Flight Booking: Kquika’s solution to getting the Cheapest Ticket Every Time.

Kquika’s logo

Machine Learning-Based Intelligent Marketing Campaigns with 2x Higher Conversion rate


Technology In Medicine Including AI Can Adversely Affect Physician Abilities And Patient Outcomes

Nivea Star Trekker — Incorrect ratings?