Leetcode: Remove Nth Node From End of List (C++ hash map approach)

Delgersaikhan
2 min readAug 25, 2020

Hey boys! Another problem solution from leetcode.com.

I have focused on doing it in one pass. As you can read the problem description the given index would be counted from end of the linked list which makes the problem more interesting.

Algorithm

  1. Save all node in hash map through iteration and store the size of linked list.
        ListNode * it = head;
int counter=1;
while(it) {
hash[counter]=it;
counter++;
it=it->next;
}

2. Get the map indices of side nodes of a node that supposed to be removed.

            int prev = counter-n-1;
int next = counter-n+1;
remove(hash[prev], hash[next]);

3. Then just remove the node and return head pointer.

    void remove(ListNode* prev, ListNode* next = NULL) {
//hayg deerh node iin next ni soligdono
(*prev).next=next;
}
return head;

Adding some additional conditions the whole code looks like this

/**
* 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:
map<int, ListNode*> hash;
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode * it = head;
int counter=1;
while(it) {
hash[counter]=it;
counter++;
it=it->next;
}
if(counter==2){
return NULL;
}
if(counter-n-1 == 0){
head=head->next;
} else {
int prev = counter-n-1;
int next = counter-n+1;
remove(hash[prev], hash[next]);
}
return head;
}
void remove(ListNode* prev, ListNode* next = NULL) {
//hayg deerh node iin next ni soligdono
(*prev).next=next;
}
};

--

--