πŸ“ Problem Details

πŸ’­What Were My Initial Thoughts?

- iterate through the list
- insert each node into the set
- before inserting, check if the node already exists in the set
- if it does return false, otherwise continue

πŸ€”What Did I Struggle With?

~

πŸ’‘ Explanation of Solution

same as intuition

βŒ› Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(n)

πŸ’» Implementation of Solution

class Solution {
public:
    bool hasCycle(ListNode *head) {
 
     unordered_set<ListNode*> set;
 
     ListNode* curr = head;
 
     while(curr != nullptr) {
        if(set.find(curr) != set.end()) {
            return true;
        } else {
            set.insert(curr);
            curr = curr->next;
        }
     }
     return false;   
    }
};