Sort by

recency

|

1359 Discussions

|

  • + 0 comments

    This cycle detection problem feels a lot like looping mechanics in Stardew Valley daily routines and repeating patterns. Using slow/fast pointers makes those cycles much easier to visualize.

  • + 0 comments

    bool has_cycle(SinglyLinkedListNode* head) { if (!head || !head->next) return false; SinglyLinkedListNode* turtle = head; SinglyLinkedListNode* hare = head; while (hare && hare->next) { hare = hare->next->next; turtle = turtle->next; if (hare == turtle) return true; } return false; }

  • + 1 comment

    Here is a solution for C++14:

    bool has_cycle(SinglyLinkedListNode* head) {
        unordered_set<SinglyLinkedListNode*> visited;
        
        while (head) {
            if (visited.find(head) != visited.end()) { // has 'head' been visited yet?
                return true;
            }
            visited.emplace(head);
            head = head->next;
        }
        
        return false;
    }
    
  • + 1 comment

    There is not such good explaining about the input: First suposition: By considering the input as all elements beign the array, it only succeeds two cases. Second suposition: By considering input as {n0, item0, ... , itemn0, n1, item0, ... , itemn1, etc} it also fails.

    Not sure how to process the input.

  • + 0 comments

    def has_cycle(head): slow = head fast = head

    while fast != None and fast.next != None:
        slow = slow.next
        fast = fast.next.next
    
        if slow == fast:
            return 1  # Cycle detected
    
    return 0  # No cycle