A 2-ms recursive solution in C without extra pointers or loops

  • 1
      int countAndRemove(struct ListNode *node, int n){
                if(!node->next) return n-1;
                int rest = countAndRemove(node->next, n);
                if(rest == 0)  node->next = (node->next)->next;
                return rest-1;
        struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
                    return (countAndRemove(head, n) == 0)? head->next : head;

  • 0

    Nice solution !
    Is it some kind of dynamic programming ?

  • 0

    merci well actually I don't know much about dynamic programming stuff.
    I would just call it backward counting.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.