Oracle Interview Question
Software Engineer / DevelopersCountry: -
Interview Type: In-Person
/* Function to remove duplicates from a unsorted linked list */
void removeDuplicates(struct node *start)
{
struct node *ptr1, *ptr2, *dup;
ptr1 = start;
/* Pick elements one by one */
while(ptr1 != NULL && ptr1->next != NULL)
{
ptr2 = ptr1;
/* Compare the picked element with rest of the elements */
while(ptr2->next != NULL)
{
/* If duplicate then delete it */
if(ptr1->data == ptr2->next->data)
{
/* sequence of steps is important here */
dup = ptr2->next;
ptr2->next = ptr2->next->next;
free(dup);
}
else /* This is tricky */
{
ptr2 = ptr2->next;
}
}
ptr1 = ptr1->next;
}
}
struct listNode
{
int data;
struct listNode *next;
};
typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;
void renoveDuplicates(ListNodePtr sptr)
{
map<int,bool> M;
ListNodePtr previous=NULL;
while(sptr!=NULL)
{
if(M[sptr->data]==true)
{
cout<<"i m here"<<endl;
previous->next=sptr->next;
}
else
{
M[sptr->data]=true;
previous=sptr;
}
sptr=sptr->next;
}
}
If you do have some memory available, you can use a bit vector and iterate the linked list only once.
1. Create a bit vector with size equal to the max size that a node can store (e.g., if a node stores 32 bit integer values, create a bit vector that is 2^32 bits long - 0.5 GB).
2. Iterate through the linked list. For each node, check if the respective bit is set. If the bit is not set, set it and move to the next node. If the bit is set, make the previous node to point to the next one (i.e., delete the current node) and move to the next node.
- .·´¯`·.´¯`·.¸¸.·´¯`·.¸><(((º> January 28, 2014