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

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

  • 0

    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.