Remove Nth Node From End of List

Problem

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example 1:

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

Input: head = [1], n = 1
Output: []

Example 3:

Input: head = [1,2], n = 1
Output: [1]

Constraints:

  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

Follow up: Could you do this in one pass?

Solution

This problem was a bit difficult for me.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        var fast = head;
        ListNode slow = null;
        var i = 0;

        while (fast != null) {
            i += 1;
            fast = fast.next;
            if (i > n) {
                if (slow == null) {
                    slow = head;
                } else {
                    slow = slow.next;
                }
            }
        }

        if (slow == null) {
            return head.next;
        }

        if (slow.next.next == null) {
            slow.next = null;
        } else {
            slow.next.val = slow.next.next.val;
            slow.next.next = slow.next.next.next;
        }

        return head;
    }
}

Recent posts from blogs that I like

An unnatural history of footwear in paintings 2

Kabkabs worn by Turkish ladies in the Hammam, from-frou high heels with pointed toes, red shoes unsuited to the mountains, shiny black patent leather shoes, and kinky black boots.

via The Eclectic Light Company

You have to beat the models at something

In 2025, I wrote that software engineers ought to be assessed by “value over replacement”: not how much money they made for their company, but how much they would have made compared to the average engineer in their position. I’ve always found it vaguely silly when engineers put “built a product that...

via Sean Goedecke

How big are factorials?

The other day, I found myself wondering how big 52! (52 factorial) is, and that led me to ponder how these could be estimated without a calculator or a computer. It turns out there’s some fairly interesting math behind being able to estimate the size (number of digits) of a factorial reasonably accu...

via Eli Bendersky