3
\$\begingroup\$

I was wondering if detecting a loop in a linked list using a HashSet is better than using two pointers?

        HashSet<Integer> set = new HashSet<Integer>();
    LinkedListNode current = head;
    while(current != null) {
        if(current.next != null) {
            if(set.contains(current.next.data)) {
                return current.next; // this has been seen so there is a loop.
            }
            set.add(current.next.data);
        }
        current = current.next;
    }
    return null;    
\$\endgroup\$
5
\$\begingroup\$

I think instead of adding integers to the Hashset, what we should do is insert a LinkedListNode instance into the Hashset and then to detect a loop we check whether the current node exists in the Hashset or not, if it does then there's a loop

 HashSet<LinkedListNode> set = new HashSet<LinkedListNode>();
    LinkedListNode current = head;
    while(current != null) {
        if(current.next != null) {
            if(set.contains(current.next)) {
                return current.next; // this has been seen so there is a loop.
            }
            set.add(current.next);
        }
        current = current.next;
    }
    return null;
\$\endgroup\$
3
\$\begingroup\$

Incorrect

This code will return a loop where none exists, if the list contains two of the same integer. For example, take this list without a loop:

1 -> 2 -> 3 -> 2 -> null

When your code reaches the 2nd 2, it will think it detected a loop.

Next not needed

In your code you look ahead to "next" unnecessarily. In fact, you are even skipping over the first element of the list, which could lead to returning the wrong node. Your code could simplify to:

HashSet<Integer> set = new HashSet<Integer>();
LinkedListNode current = head;
while (current != null && !set.contains(current.data)) {
    set.add(current.data);
    current = current.next;
}
return current;

Although remember that this code has the bug mentioned above, so it merely checks for duplicate elements, not for the existence of a loop.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.