Remove Nth Node from the End of a Linked List

Given a singly linked list, write a code to remove nth node from the end of a linked list. In this problem, you can assume the value of n is always valid.

For example –

In this example, the input linked list has four nodes and we have to remove 2nd node from the end.

Input –

15 -> 9 -> 8 -> 5 -> NULL , N = 2

After removing second node (node whose value is 8) from the end, the output is

15 -> 9 -> 5 -> NULL

Remove Nth Node from the End of a linked list

We have discussed the problem statement. Let’s discuss multiple approaches and their time and space complexities to solve this problem.

Programming Video Tutorials

Reverse a linked list

Remove nth node from end of a linked list video tutorial

Remove Nth Node from End of a Linked List – Java Code

The easiest approach is to traverse a linked list twice to solve this problem.

In the first traversal, we count the number of nodes present in a linked list. Once we know the count of elements in a list, the next step is to remove the nth node from the end.

The time complexity of this approach is O(n) and its space complexity is O(1).

Let’s write its java code.

Programming questions on linked list

Programming questions on binary tree

Remove Nth Node from End of List in Single Traversal – Java Code

Let’s improve our previous solution and solve this problem in a single traversal. To solve this problem in a single traversal/pass we are going to use two pointers (slow and fast).

First, move the fast pointer by n steps. After that move fast and slow pointer by one step until fast pointer does not point to null.

When the fast pointer reaches the end the slow pointer is exactly the nth node from the end.

The time complexity of removing the nth node from the end is O(n) and its space complexity is O(1).

Remove duplicates from a sorted linked list

Remove Nth Node from List End InterviewBit Solution – Java Code

The same problem is present in interviewbit where we have to remove the nth node from list end.

The only difference is, If the value of n is greater than the size of the list, then we have to remove the first node of the list.

Remove nth node from end of a linked list video tutorial

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.