The Indian Engineer

Problem 82 Remove Duplicates From Sorted List II

Posted on Last edited 2 mins

Two-Pointer Two-Pointers Linked-List

Problem Statement

Link - Problem 82

Question

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

Example 1

image1

Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]

Example 2

image2

Input: head = [1,1,1,2,3]
Output: [2,3]

Constraints

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == nullptr || head->next ==nullptr)
            return head;
        ListNode* dummy = new ListNode(-1);
        dummy->next = head;

        ListNode* prev = dummy;
        ListNode* curr = head;

        while(curr != nullptr && curr->next!=nullptr){
            if(curr->val != curr->next->val){
                prev = curr;
                curr=curr->next;
            }
            else{
                while(curr!=nullptr && prev->next->val == curr->val){
                    curr = curr->next;
                }
                prev->next = curr;
            }
        }
        return dummy->next;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Two Pointers O(n) O(1)

Explanation

1. Intuition

2. Implementation