AfterAcademy Tech
•
18 Feb 2020

Difficulty: Medium
Asked in: Myntra, Oracle, Visa, Adobe
Problem Description: Given a sorted linked list which has some duplicate elements, your task is to remove all the duplicate elements from the given Linked List. As a result of solving this problem, your Linked List will only have all unique elements.
For example:
Input: 2->3->3->4->5->7->7->9->NULL
Output: 2->3->4->5->7->9->NULL
Explanation: All the duplicate elements have been removed.
Similarly,
Input: 4->7->9->9->10->11->11->NULL
Output: 4->7->9->10->11->NULL
Possible follow-up questions to ask the interviewer: →
We are going to discuss two possible ways to solve this problem: →
Solution idea
In this approach, we will iteratively traverse the entire Linked List. Going to each node one by one, we will compare that node with the adjacent node. If the data value for both the nodes are the same it means that the node is duplicate. We will then de-link one of the duplicate nodes and will follow the same procedure for the rest of the nodes.
Solution steps
Pseudo-code
ListNode removeDuplicatedFromLL(ListNode head)
{
ListNode current = head;
while(current!=NULL && current.next!=NULL)
{
ListNode NextNode = NULL;
if(current.data == current.next.data)
{
NextNode = current.next.next
delete current.next;
current.next = NextNode;
}
else
current = current.next
}
}
Complexity Analysis
Time Complexity: O(N), where N is the size of the array.
Space Complexity: O(1)(Why?)
Critical ideas to think!
Solution idea
Here also the basic approach is completely the same, the only difference is in the implementation. The above solution is implemented by using an iterative solution, in this, we will make a recursive solution. For a recursive solution, we need to think about the base condition, an easy operation for us to do and the sub-task that we will leave on recursion. The operation is to compare two nodes and to see if the data values are the same or not.
Solution steps
Pseudo-code
void removeDuplicatesFromLL(ListNode head)
{
if(head==NULL or head.next==NULL)
return
if(head.data == head.next.data)
{
ListNode NextNode = head.next.next
delete head.next
head.next = NextNode
removeDuplicatesFromLL(head)
}
else
removeDuplicatesFromLL(head.next)
}Complexity Analysis
Time Complexity: O(N)
Space Complexity: O(N)

Happy Coding! Enjoy Algorithms!!
AfterAcademy Tech
This is an interview problem asked in companies like Google, Microsoft, Amazon. The problem is to remove duplicates from a sorted array or list.

AfterAcademy Tech
Sort a linked list using insertion sort and return its head.

AfterAcademy Tech
Given a Linked List, your task is to find whether the given singly linked list is a palindrome or not. This is an interview problem asked in many companies like Amazon, Microsoft, Adobe, Flipkart and other big companies.

AfterAcademy Tech
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
