Saturday, 31 January 2015

Remove Duplicates from a linked lisr

With a HashSet as buffer = Time = O(n), space = O(n)
Using two pointer technique - running method -  Time = O(n^2) Space = O(1)

// with HashSet as buffer
public static removeDuplicates(LinkedListNode head)
{
    HashSet<Integer>set =  new HashSet<Integer>();
    LinkedList ptr = head, prev = null;
    while(ptr != null )
    {
   
        if(set.contains(ptr.data))
        {
            prev.next = ptr.next;
        }
        else
        {
            set.add(ptr.data);
            prev = ptr;
        }
        ptr = ptr.next;
    }
}


//using 2-point pointer running technique

public static removeDuplicates(LinkedListNode head)
{
    LinkedList p1 = head;
    LinkedList p2 = p1.next ;
    LinkedList prev = null
    while( p1.next != null )
    {
        while( p2 != null )
        {
            if( p2.data == p1.data )
            {
                prev.next  = p2.data;
            }
            else
            {
                prev = p2;
            }
            p2  = p2.next;
           
        }
    }
}

No comments:

Post a Comment