← Home

82. Remove Duplicates from Sorted List II

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
82

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 82. Remove Duplicates from Sorted List II, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • two pointer

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are deleteDuplicates.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//two pointer
02//Runtime: 8 ms, faster than 93.49% of C++ online submissions for Remove Duplicates from Sorted List II.
03//Memory Usage: 11.5 MB, less than 15.28% of C++ online submissions for Remove Duplicates from Sorted List II.
04/**
05 * Definition for singly-linked list.
06 * struct ListNode {
07 *     int val;
08 *     ListNode *next;
09 *     ListNode() : val(0), next(nullptr) {}
10 *     ListNode(int x) : val(x), next(nullptr) {}
11 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
12 * };
13 */
14class Solution {
15public:
16    ListNode* deleteDuplicates(ListNode* head) {
17        ListNode* dummy = new ListNode(-1);
18        
19        dummy->next = head;
20        
21        ListNode *slow = dummy, *fast = head;
22        
23        while(fast){
24            bool dup = false;
25            do{
26                //assume fast's val is not duplicate
27                dup = false;
28                while(fast && fast->next && fast->val == fast->next->val){
29                    fast = fast->next;
30                    dup = true;
31                }
32                //if fast's val is duplicate, we discard it and find from next
33                if(dup) fast = fast->next;
34                // cout << "fast: " << fast->val << endl;
35            }while(dup);
36            //now fast is nullptr or it points to non-duplicate value
37            
38            // cout << slow->val << " <- " << fast->val << endl;
39            slow->next = fast;
40            slow = slow->next;
41            //need to check if fast is nullptr
42            if(fast) fast = fast->next;
43        }
44        
45        return dummy->next;
46    }
47};
48
49//cleaner
50//https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/discuss/28335/My-accepted-Java-code
51//Runtime: 12 ms, faster than 63.08% of C++ online submissions for Remove Duplicates from Sorted List II.
52//Memory Usage: 11.4 MB, less than 19.33% of C++ online submissions for Remove Duplicates from Sorted List II.
53class Solution {
54public:
55    ListNode* deleteDuplicates(ListNode* head) {
56        ListNode* dummy = new ListNode(-1);
57        
58        dummy->next = head;
59        
60        ListNode *slow = dummy, *fast = head;
61        
62        while(fast){
63            while(fast && fast->next && fast->val == fast->next->val){
64                fast = fast->next;
65            }
66            
67            if(slow->next == fast){
68                //fast points to non-duplicate value
69                //accept it and move forward
70                slow = slow->next;
71            }else{
72                //fast points to duplicate value
73                //so discard it and temporarily connect slow and fast->next
74                slow->next = fast->next;
75                //move fast forward
76                //in next iteration, we still need to check whether fast points to duplicate value
77                fast = fast->next;
78            }
79        }
80        
81        
82        return dummy->next;
83    }
84};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.