Java solution using HashSets

  • 0

    The idea here is simple. Keep adding nodes as observed, to a HashSet. As soon as you find you've come to a node thats already in the HashSet, you've reached the point where the cycle started

    public class Solution {
        public ListNode detectCycle(ListNode head) {
            HashSet<ListNode> set = new HashSet<ListNode>();
            ListNode current = head;
            while(current != null) {
                if(!set.contains(current)) {
                    current =;
                else {
                    return current;
            return null;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.