~/coding-interview/leetcode-remove-nth-node-from-last.md

Remove nth Node from Last - Leet Code Solution

// TL;DR

Two-pointer gap technique — advance the first pointer n steps ahead, then move both together. When first hits the end, second is at the node before the target. One pass, O(n).

Remove nth Node from Last - Leet Code Solution

Problem Statement

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

Solution

There can be many solution for this. Lets start with a brute force simple solution.

Algorithm-1

You can simply iterate full link list, and count its length. Lets say it: L Calculate L-n. And, move pointer from head to this many times. This node will be the one who has to be deleted.

This requires 2 iteration. Although complexity is still O(n). But, we can think of more optimized version of this algorithm.

Algorithm-2

We can leverage two pointer concept. Where one pointer moves ahead of first pointer. We just need to keep a distance of ‘n’ between two pointers.

  • Start with two pointers: p1, p2
  • Keep p1 at head, move p2 ahead one step at a time.
  • Move p2 n times.
  • Now, difference between p1 and p2 is ‘n’
  • We now have to move both the pointers ahead with same speed. i.e. one step at a time.
  • When 2nd pointer reaches end of link list, the first pointer will be at the desired node that we want to delete.

Lets look at the code:

public class ListNode {
	int val;
	ListNode next;
	ListNode(int x) { val = x; }
 }
public ListNode removeNthFromEnd(ListNode head, int n) {
	ListNode h = head;
	ListNode fast = head;
	ListNode prev = null;

	for (int i=0; i<n; i++) {
		fast = fast.next;
	}
	while (fast != null) {
		prev = h;
		h = h.next;
		fast = fast.next;
	}
	if (prev == null) {
		//special condition where first pointer is at the head only. And, we want to delete head
		return head.next;
	}

	prev.next = h.next;
	return head;
}

Above code does assume that length of list is always greater than equal to ‘n’.

Performance

BTW, this code submission to leetcode turns out to be the fastest.

Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Nth Node From End of List.
Memory Usage: 34.8 MB, less than 100.00% of Java online submissions for Remove Nth Node From End of List.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Leetcode - Split a String Into the Max Number of Unique Substrings

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement Given a string s, return the maximum number of unique…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…