When life gives lemons, make lemonade. O(n) time and O(1) space


  • 0
    R
    public ListNode detectCycle(ListNode head) {
            if(head == null)    return null;
            
            HashMap<ListNode,ListNode> hm=new HashMap<ListNode,ListNode>();
            
            while(head!=null){
                if(hm.containsKey(head))   return head;
                else hm.put(head,head);
                head=head.next;
            }
        
            return head;
        }
    

  • 0
    N

    With the use of Hashmap I believe this is O(n) space as well, as in the worst case you fill the map with all nodes but the last.


Log in to reply
 

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