Linked List Cycle

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

Follow up:
Can you solve it without using extra space?

``````
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head) return false;
ListNode* l1 = head;
ListNode* l2 = head;
ListNode* l3 = head;

while(head->next && head->next->next && head->next->next->next)
{
if(l1->next) l1 = l1->next;
else return false;
if(l2->next && l2->next->next) l2 = l2->next->next;
else return false;
if(l3->next && l3->next->next && l3->next->next->next)
l3 = l3->next->next->next;
else return false;

if(l1 == l2 || l2 == l3 || l1 == l3) return true;
}
return false;
}
};
12ms
``````

Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?

``````
class Solution {
public:
ListNode *hasCycle(ListNode *head) {
if(!head) return NULL;
ListNode* l1 = head;
ListNode* l2 = head;

while(head->next && head->next->next && head->next->next->next)
{
if(l1->next) l1 = l1->next;
else return NULL;
if(l2->next && l2->next->next) l2 = l2->next->next;
else return NULL;

if(l1 == l2) return l1;
}
return NULL;
}
ListNode *detectCycle(ListNode *head) {
ListNode* cycle = hasCycle(head);
if(!cycle) return NULL;
if(cycle == head) return cycle;

ListNode* ptr = head;
ListNode* cycleStart = cycle;

while(ptr)
{
do{
if(ptr == cycle) return ptr;
cycle = cycle->next;
}while(cycle != cycleStart);
cycle = cycleStart = cycleStart->next;
ptr = ptr->next;
}
}
};
72ms
``````

Prove:

``````
class Solution {
public:
ListNode *hasCycle(ListNode *head) {
if(!head) return NULL;
ListNode* l1 = head;
ListNode* l2 = head;

while(head->next && head->next->next && head->next->next->next)
{
if(l1->next) l1 = l1->next;
else return NULL;
if(l2->next && l2->next->next) l2 = l2->next->next;
else return NULL;

if(l1 == l2) return l1;
}
return NULL;
}
ListNode *detectCycle(ListNode *head) {
ListNode* cycle = hasCycle(head);
if(!cycle) return NULL;
if(cycle == head) return cycle;

ListNode* ptr = head;

while(ptr != cycle)
{
ptr = ptr->next;
cycle = cycle->next;
}
return ptr;
}
};
12ms
``````

Find the Duplicate Number

``````
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int s_index, s_val, f_index, f_val;
s_index = f_index = 0;
s_val = f_val = nums[0];

do
{
s_index = nums[s_index];
f_index = nums[f_index];
f_index = nums[f_index];
}while(s_index != f_index);

s_index = 0;
while(nums[s_index] != nums[f_index])
{
s_index = nums[s_index];
f_index = nums[f_index];
}

return nums[s_index];
}
};
12ms
``````