Solution: Remove Duplicates from Sorted List
Let's solve the Remove Duplicates from Sorted List problem using the In-Place Manipulation of a Linked List pattern.
We'll cover the following
Statement
Given the Head
of a sorted linked list, remove all duplicates such that each element appears only once, and return the list in sorted order.
Constraints:
n
, where n
is the number of nodes in the list.Node.Data
The list is guaranteed to be sorted in ascending order.
Solution
A key point that will help us solve this problem is that the linked list is sorted so that all duplicates will appear consecutively. This allows us to easily identify duplicates by comparing each node with its next node. We can use and manipulate the pointers to modify the original list directly in a single pass.
The solution works as follows:
The
current
pointer is initialized to theHead
of the linked list, which will allow traversal through the list.Traverse the linked list to look for duplicates. Before updating the pointer to move to the next node, ensure that both
current
andcurrent.Next
are notnil
. The process is as follows:If the current node's value is the same as the next node's, i.e.,
current.Data
current.Next.Data
, a duplicate is detected. Remove this duplicate by skipping the next node, i.e., by setting thecurrent.Next
tocurrent.Next.Next
.If the current node and the next node have different values, there are no duplicates, so move to the next node by setting
current
tocurrent.Next
.
Continue this process until either
current
orcurrent.Next
isnil
, at which point the end of the list has been reached. Return the modifiedHead
of the list.
Why does the solution work?
One might wonder how skipping a node during traversal removes it from the actual list. When we assign current = Head
, we're setting current
to refer to the same memory location as the node Head
. Therefore, any changes made to the node that current
points to will reflect in the actual list.
The expression current.Next = current.Next.Next
modifies the Next
pointer of the node that the current
points to. This means we're telling the node currently pointed to by current
to skip over the duplicate node and point to the next one. By doing this, we're altering the connections in the linked list itself.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.