Remove Duplicates from Sorted List

Updated on 27 June, 2025
Remove Duplicates from Sorted List header image

Problem Statement

Dealing with linked lists, the issue often arises of having duplicated values that need elimination while maintaining the sequential integrity of the list. In this specific problem, you are given the head of a sorted linked list. Your task is to remove all duplicate nodes, maintaining only unique values, and ensuring that the modified linked list remains sorted in ascending order. Thus, the function must return a new linked list, or the modified original one, with no duplicate values, preserving the order. The list is already sorted, which means each duplicate element is adjacent to its duplicates.

Examples

Example 1

Input:

head = [1,1,2]

Output:

[1,2]

Example 2

Input:

head = [1,1,2,3,3]

Output:

[1,2,3]

Constraints

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

Approach and Intuition

Given that the list is already sorted, the basic strategy can leverage this order to simplify the removal of duplicates. Here's a concise step-by-step breakdown:

  1. If the head is null, return immediately as there's nothing to process.
  2. Initialize two pointers: one, current, to traverse the list, and next_item as current.next.
  3. While traversing through the linked list:
    • Compare the value of current with next_item.
    • If they are equal, it indicates a duplicate. Adjust the next pointer of current to skip the next_item node, thus removing it from the list.
    • If they are not equal, just move current to next_item.
    • update next_item to the next node in the list (current.next).
  4. Stop when current reaches the last node.

The intuition behind using two pointers is that it allows us to modify the links between nodes directly, skipping over duplicates, without the need for additional data structures. This method also ensures that the space complexity remains constant, ideal for handling large linked lists efficiently. The process as outlined is straightforward due to the initial condition of the list being sorted, enabling a linear, one-pass algorithm to resolve the problem effectively.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    ListNode* removeDuplicates(ListNode* head) {
        ListNode* cursor = head;
        while (cursor != NULL && cursor->next != NULL) {
            if (cursor->next->val == cursor->val) {
                cursor->next = cursor->next->next;
            } else {
                cursor = cursor->next;
            }
        }
        return head;
    }
};

This guide provides a concise approach to removing duplicates from a sorted linked list using C++. Follow the outlined method to achieve the desired result:

  • Start by establishing a cursor pointer initialized to the head of the list. This will traverse the list checking for duplicates.
  • Employ a while loop to continue as long as the cursor and the next node are not null.
  • Within the loop, check if the current node (cursor) and the next node (cursor->next) have the same value. If they do, set the next pointer of the cursor to skip the duplicate node (cursor->next->next), effectively removing the duplicate.
  • If the nodes are not duplicates, simply move the cursor to the next node.
  • Finally, return the potentially modified head of the list. This operation ensures that all consecutive duplicates are removed, and retains only unique values in their first occurrences.

The provided code efficiently maintains the order of the nodes and only removes duplicates, ensuring that the integrity and sorted order of the list are upheld.

java
class Solution {
    public ListNode removeDuplicates(ListNode head) {
        ListNode pointer = head;
        while (pointer != null && pointer.next != null) {
            if (pointer.next.val == pointer.val) {
                pointer.next = pointer.next.next;
            } else {
                pointer = pointer.next;
            }
        }
        return head;
    }
}

The given Java code defines a solution for removing duplicate nodes from a sorted linked list. The function removeDuplicates takes the head of the linked list as a parameter and returns the modified list with duplicates removed. The implementation uses the following steps to achieve this:

  1. Initialize a pointer variable to point to the head of the list.
  2. Traverse the list using a while loop which continues as long as pointer is not null and there is a next node in the list.
  3. Within the loop, check if the current node (pointer) has the same value as the next node. If they match, the link to the next node is updated to skip the duplicate, effectively removing it from the list.
  4. If the values do not match, the pointer is moved to the next node.
  5. Finally, the modified head of the list, which now has duplicates removed, is returned.

This approach efficiently cleans the linked list in-place with O(1) additional space complexity and O(n) time complexity, where n is the number of nodes in the list.

c
struct ListNode* removeDuplicates(struct ListNode* start) {
    struct ListNode* cursor = start;
    while (cursor != NULL && cursor->next != NULL) {
        if (cursor->next->val == cursor->val) {
            cursor->next = cursor->next->next;
        } else {
            cursor = cursor->next;
        }
    }
    return start;
}

The provided solution in C focuses on removing duplicates from a sorted linked list. It utilizes a simple in-place algorithm to manipulate the list such that it retains only unique elements. Here's a breakdown of how this function operates:

  • Initialize a pointer, cursor, to point at the start of the list.
  • Traverse the list using cursor, as long as cursor is not NULL and cursor's next node exists.
  • Within the loop, compare the value of the current node (cursor->val) with the value of the next node (cursor->next->val).
  • If they are identical, bypass the duplicate by making cursor->next point to cursor->next->next.
  • If the next value is different from the current one, simply move cursor to the next node.
  • The traversal continues until the end of the list is reached, ensuring all duplicates are removed.
  • Finally, the function returns the modified list beginning from start, which is now stripped of any duplicates.

This approach efficiently handles sorted lists, leveraging the property that duplicates are adjacent. The in-place modification helps in minimizing space complexity, making the solution efficient in terms of both time and space. Ensure that proper handling and freeing of the bypassed nodes occur outside of this function to avoid memory leaks.

js
var removeDuplicates = function (listHead) {
    let currentNode = listHead;
    while (currentNode !== null && currentNode.next !== null) {
        if (currentNode.next.val === currentNode.val) {
            currentNode.next = currentNode.next.next;
        } else {
            currentNode = currentNode.next;
        }
    }
    return listHead;
};

The provided JavaScript function removeDuplicates efficiently removes duplicate elements from a sorted linked list. It takes the head of the list as an input. During its operation, the function traverses the list, using a while loop, to compare consecutive nodes. If two consecutive nodes have the same value, it removes the duplicate by skipping the node and linking the current node directly to the next non-duplicate node. This process continues until the end of the list is reached. The function ensures the original sorted order is maintained and returns the head of the modified list without duplicates.

python
class Solution:
    def removeDuplicates(self, start: ListNode) -> ListNode:
        node = start
        while node is not None and node.next is not None:
            if node.next.val == node.val:
                node.next = node.next.next
            else:
                node = node.next
        return start

This Python code defines a solution to remove duplicates from a sorted linked list. The function removeDuplicates starts by setting a pointer node at the beginning of the list. As you traverse through the list using a while loop, check if the current node's value is the same as the next node's value. If they match, the next node is skipped by adjusting the next pointer of the current node, effectively removing the duplicate. If they don't match, move to the next node in the list. The process continues until the end of the list is reached. The modified list, now without any duplicates, is returned.

This approach ensures that the list remains sorted and all duplicates are removed without the use of any additional data structures, maintaining a space complexity of O(1) and a time complexity of O(n), where n is the number of nodes in the list.

Comments

No comments yet.