1. Brute Force — Hash Set Visited Node Tracking
Intuition
Traverse the list and insert each node address into a hash set. The first node that is already in the set is the exact entry point of the cycle.
Algorithm
- Step 1: Create an empty
HashSetof node pointers. - Step 2: Initialize
curr = head. - Step 3: While
curr != null: - a. If
set.contains(curr), returncurr(cycle entry). - b. Add
currtoset. - c. Advance
curr = curr.next. - Step 4: Return
null(no cycle).
#include <iostream>#include <unordered_set> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {}}; class Solution {public: ListNode *detectCycle(ListNode *head) { unordered_set<ListNode*> visited; ListNode* curr = head; while (curr) { if (visited.count(curr)) { return curr; } visited.insert(curr); curr = curr->next; } return nullptr; }}; int main() { ListNode* n1 = new ListNode(3); ListNode* n2 = new ListNode(2); ListNode* n3 = new ListNode(0); ListNode* n4 = new ListNode(-4); n1->next = n2; n2->next = n3; n3->next = n4; n4->next = n2; Solution sol; ListNode* entry = sol.detectCycle(n1); cout << "Brute Force Entry: " << (entry ? to_string(entry->val) : "null") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Visits each node once in O(N). Hash set queries and insertions take O(1) average time. - Space complexity:
O(N)— Allocates a hash set storing up to N node pointer addresses.
Why Brute Force Doesn't Scale:
Hash sets allocate auxiliary buckets and trigger cache evictions.
For N = 10,000, Floyd's 2-phase algorithm executes in <0.08ms.