LinkedLists Greedy CycleDetection
Problem
Solution
Hash Set - O(n) time - O(n) space
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> list;
while(head) {
if (list.count(head)) return true;
else {
list.insert(head);
head = head->next;
}
}
return false;
}
};
Two Pointer Floyd’s Cycle Detection- O(n) time - O(1) space
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};