← Home

19. Remove Nth Node From End of List

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

The trick here is to name the state correctly, then let the implementation follow. For 19. Remove Nth Node From End of List, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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:

  • linked list

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are removeNthFromEnd.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • 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. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

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(L), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//linked list
02//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Remove Nth Node From End of List.
03//Memory Usage: 11 MB, less than 11.61% of C++ online submissions for Remove Nth Node From End of List.
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* removeNthFromEnd(ListNode* head, int n) {
17        ListNode* cur = head;
18        int len = 0;
19        
20        while(cur){
21            ++len;
22            cur = cur->next;
23        }
24        
25        if(n == len){
26            //delete the head
27            ListNode* ans = head->next;
28            delete head;
29            return ans;
30        }
31        
32        cur = head;
33        for(int i = 0; i < len; ++i){
34            if(i == len-n-1){
35                //the node previous to the node to be deleted
36                ListNode* to_delete = cur->next;
37                cur->next = cur->next->next;
38                delete to_delete;
39                break;
40            }
41            cur = cur->next;
42        }
43        
44        return head;
45    }
46};
47
48//Approach 1: Two pass algorithm
49//use dummy head to avoid corner case
50//Runtime: 8 ms, faster than 35.30% of C++ online submissions for Remove Nth Node From End of List.
51//Memory Usage: 10.9 MB, less than 18.24% of C++ online submissions for Remove Nth Node From End of List.
52//time: O(L), space: O(1)
53/**
54 * Definition for singly-linked list.
55 * struct ListNode {
56 *     int val;
57 *     ListNode *next;
58 *     ListNode() : val(0), next(nullptr) {}
59 *     ListNode(int x) : val(x), next(nullptr) {}
60 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
61 * };
62 */
63class Solution {
64public:
65    ListNode* removeNthFromEnd(ListNode* head, int n) {
66        ListNode* dummy = new ListNode();
67        dummy->next = head;
68        
69        ListNode* cur;
70        int len = 0;
71        
72        cur = dummy->next;
73        while(cur){
74            ++len;
75            cur = cur->next;
76        }
77        
78        // cout << "len: " << len << endl;
79        
80        cur = dummy;
81        for(int i = 0; i < len; ++i, cur = cur->next){
82            //i is 1-based
83            // cout << i << " : " << cur->val << endl;
84            if(i == len-n){
85                //this is the node previous to the node to be deleted
86                ListNode* tmp = cur->next;
87                cur->next = cur->next->next;
88                delete tmp;
89                break;
90            }
91        }
92        
93        return dummy->next;
94    }
95};
96
97//Approach 2: One pass algorithm
98//Runtime: 4 ms, faster than 85.69% of C++ online submissions for Remove Nth Node From End of List.
99//Memory Usage: 11.1 MB, less than 5.24% of C++ online submissions for Remove Nth Node From End of List.
100//time: O(L), space: O(1)
101/**
102 * Definition for singly-linked list.
103 * struct ListNode {
104 *     int val;
105 *     ListNode *next;
106 *     ListNode() : val(0), next(nullptr) {}
107 *     ListNode(int x) : val(x), next(nullptr) {}
108 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
109 * };
110 */
111class Solution {
112public:
113    ListNode* removeNthFromEnd(ListNode* head, int n) {
114        ListNode* dummy = new ListNode();
115        dummy->next = head;
116        
117        ListNode *slow = dummy, *fast = dummy;
118        
119        for(int i = 0; i < n+1; ++i){
120            fast = fast->next;
121        }
122        //slow and fast are n+1 apart
123        
124        while(fast){
125            slow = slow->next;
126            fast = fast->next;
127        }
128        //slow is n+1 from tail->next, so n from tail
129        //so it's (n+1)-last node
130        
131        ListNode* tmp = slow->next;
132        slow->next = slow->next->next;
133        delete tmp;
134        
135        return dummy->next;
136    }
137};

Cost

Complexity

Time
O(L), space: O(1)
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.