JavaScript one pass using recursion


  • 0
    var removeNthFromEnd = function(head, n) {
        const dummy = new ListNode();
        dummy.next = head;
        helper(dummy, n);
        return dummy.next;
    };
    
    function helper(node, n) {
        if (!node) return 0;
        const i = helper(node.next, n);
        if (i === n) {
            node.next = node.next ? node.next.next : null;
        }
        return i + 1;
    }
    

    O(len) space for the call stack.


Log in to reply
 

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