Scrivio Interview library
Linked listsLinked listsReported 26 times · 15 min read · updated 14 November 2026

Find the nth node from the end of a linked list.

1What the nth node from the end means

Imagine walking along a long goods train on a foggy morning. You can see the coach you are standing beside and the coupling to the next one, but not the end of the train. Someone asks you to stop at the second coach from the end. You cannot look ahead to find the end, and you cannot walk backwards along the couplings, because each coupling only tells you which coach comes next. That is exactly the position this problem puts us in.

A singly linked list is that train. Each coach is a node, which holds a value and a reference called next, the coupling to the following node. The last node's next is null, Java's word for nothing. We are given the head, the first node, and a number n, and we must return the node that is n places from the end, counting the last node as 1.

The word singly matters. Each node knows only the node after it, so we can only walk forwards, and we do not know the length until we have walked to the end. The problem looks harder than it is because of that fog. Once we see one small trick, the whole solution is a pair of short loops.

PictureThe example list and the node we want

Counting from the end, 50 is the 1st node, 40 the 2nd, 30 the 3rd, and so on back to 10, the 5th.

  1. 1020304050head
    n
    2
    from the end
    50 is 1st, 40 is 2nd
    answer
    node 40

    1We are handed only head, the first node, and n = 2. Counting back from the end, 50 is 1st and 40 is 2nd, so the answer is the node holding 40.

What to assume

Does n = 1 mean the last node?
We assume so.
What if the list has fewer than n nodes, or is empty?
We return null rather than throwing an exception.
Must we walk the list only once, perhaps because it arrives as a stream?
We aim for one pass. And we return the node itself, not just its value, so that the caller can use or remove it.

Let us work the example by hand. The list is 10 -> 20 -> 30 -> 40 -> 50 and n is 2. Counting back from the end, 50 is 1st, 40 is 2nd, 30 is 3rd, 20 is 4th and 10 is 5th, so the answer is the node holding 40. With n = 1 the answer would be 50, and with n = 5 it would be 10, the head itself.

A careful candidate asks a few questions before coding. Does n = 1 mean the last node? We assume so. What if the list has fewer than n nodes, or is empty? We return null rather than throwing an exception. Must we walk the list only once, perhaps because it arrives as a stream? We aim for one pass. And we return the node itself, not just its value, so that the caller can use or remove it.

2How to spot the pattern when a position is counted from the end

When a beginner first reads this question, the natural thought is to go to the end and count back n steps. That is what we would do with an array, where the last position is simply length - 1. But in a singly linked list we cannot step backwards, and we do not know where the end is until we reach it. So the array habit does not carry over, and the question becomes how to find a place measured from an end we cannot see.

Let us take the clues in the question one at a time. The first clue is the phrase linked list, and with it the forward-only walk. Whatever we do, we will do it while moving from the head towards the end, and any node we pass is behind us unless some variable still refers to it.

The second clue is the phrase from the end. The position we want is described relative to the far end, not to the head. If we knew the length, we could change from the end into from the start, and that is the brute force. The interesting question is whether we can find the place without ever knowing the length.

The third clue is that n is fixed. The node we want is always the same distance, n steps, behind the end. A fixed distance can be carried along. If something is always exactly n steps ahead of us, then the moment it reaches the end, we are exactly n steps behind the end.

These clues point to the linked lists family, and to a technique usually called two pointers with a fixed gap. A pointer, in Java, is just a reference variable that names a node, like a finger resting on one coach. Two pointers means two such fingers. Fixed gap means they stay the same number of nodes apart the whole time. The rule to carry to other problems is this: when a position is measured from the end of something you can only walk forwards, send one pointer ahead by that distance and walk both together.

Some patterns look similar but do not fit. Fast and slow pointers also use two references, but one moves two steps for every one step of the other, so the distance between them keeps growing; that finds the middle of a list or a loop, not a fixed distance from the end. Pushing every node onto a stack, a pile where the last item in is the first out, would let us pop n times from the end, but it stores the whole list again.

3The honest first attempt, counting first and walking again

The first idea most of us have is a good one, so let us write it down properly. If the fog hides the end, walk to the end once and count the coaches. Once we know the length, the nth from the end is simply the node at position length - n from the start, counting the head as position 0. Then a second walk from the head gets us there.

Let us do it by hand. The first walk visits 10, 20, 30, 40 and 50 and counts 5. Then length - n is 5 - 2 = 3, so the second walk starts at 10 and takes three steps, to 20, 30 and finally 40. Why exactly three? Because from 40 to the end there are exactly two nodes, 40 and 50, and that is what n = 2 asks for.

Step throughCounting first, then walking again

The second walk goes back over nodes the first walk has already passed.

  1. 1020304050
    length
    5
    moves so far
    5

    1The first walk steps over every node only to count them. It finds length 5, and it has reached the end without remembering anything else.

  2. 1020304050c
    length - n
    3
    moves in all
    8
    answer
    node 40

    2The second walk starts again at the head and takes length - n = 3 steps, crossing 10, 20 and 30 a second time, and stops on 40.

Java
static Node nthByCounting(Node head, int n) {
int length = 0;
for (Node c = head; c != null; c = c.next) length++; // first walk: count the nodes
if (n < 1 || n > length) return null; // no such node
Node c = head;
for (int i = 0; i < length - n; i++) c = c.next; // second walk: length - n steps
return c;
}

It is correct, and it is worth saying aloud in an interview as a starting point. Let us count its cost. The first walk makes 5 moves and the second makes 3, so 8 moves in all for our list. For a list of L nodes that is L moves plus L - n moves, at most 2L, which grows in step with L, so the time is O(L), read as order L. It keeps only a counter and one reference, so the extra space is O(1), a constant amount.

So where is the waste, if the time is already O(L)? It is not in the number of moves. It is in the second walk, which travels over 10, 20 and 30 again, nodes we had already passed, because the first walk threw everything away except one number. If the list were a stream that can be read only once, this method would not work at all. Interviewers ask for one pass to see whether we can avoid needing the length.

4Getting to one pass, with a gap that never changes

Let us go back to the foggy train and ask a friend for help. The friend walks ahead of you by exactly n coaches and then stops. Now you both walk forwards one coach at a time, side by side in step, keeping that distance. The friend reaches the end of the train first and steps off. At that moment, where are you? You are exactly n coaches behind the place where the train ended, which is the nth coach from the end.

In code the friend is a reference called lead and you are a reference called trail. First we move lead forward n times from the head. Then we start trail at the head, so the gap between them is exactly n steps. Then we move both forward together, one step each, until lead becomes null, which means it has stepped past the last node. trail is then the answer.

Now the question a beginner usually asks. Why do we stop when lead is null, and not when lead is on the last node? Let us try both on our example and see. If we stopped with lead on 50, the last node, trail would be on 30, two steps behind 50. But 30 is the 3rd from the end, not the 2nd, because 50 itself counts as 1. Stopping one step later, when lead has left the list, puts trail on 40. So the loop test is lead != null, and the off by one error comes from mixing up these two stopping points.

Why is this correct for any list? After the first loop, lead is n steps ahead of trail. Each pass of the second loop moves both by one, so the gap stays n. When the loop ends, lead is null, one step beyond the last node. Counting back n steps from that null position lands on the node that has exactly n nodes from itself to the end, itself included. That is the definition of the nth from the end, and we never needed the length.

There is one more thing to settle, the short list. If the list has fewer than n nodes, lead runs out during the first loop. So inside that loop, before each step, we check whether lead is already null, and if it is, we return null at once. If the list has exactly n nodes, lead becomes null at the end of the first loop, the second loop never runs, and trail stays on the head, which is correct, because the head is then the nth from the end.

5Watching the two pointers walk the five-node list

The picture plays the method on 10 -> 20 -> 30 -> 40 -> 50 with n = 2. The labels under the nodes show where lead and trail are, and the panel shows the gap between them. In the first three frames only lead moves; nodes it has passed are faded because nothing refers to them any more.

Step throughTwo pointers keeping a gap of two on 10 -> 20 -> 30 -> 40 -> 50

lead goes ahead first; then lead and trail move together until lead falls off the end. When lead is null it is not drawn.

  1. 1020304050lead
    lead
    node 10
    trail
    not set yet
    gap
    0

    1We start with lead on the head, node 10. trail is not set yet. The first loop will move lead forward n = 2 times.

  2. 1020304050lead
    lead
    node 20
    trail
    not set yet
    gap
    1

    2First step of the first loop. lead is not null, so it moves to node 20. It is now one step ahead of the head.

  3. 1020304050lead
    lead
    node 30
    trail
    not set yet
    gap
    2

    3Second step. lead moves to node 30, two steps ahead of the head. The first loop has run n times and stops.

  4. 1020304050leadtrail
    lead
    node 30
    trail
    node 10
    gap
    2

    4Now trail starts on the head. Between trail on 10 and lead on 30 there are exactly two steps, and that gap will never change.

  5. 1020304050leadtrail
    lead
    node 40
    trail
    node 20
    gap
    2

    5lead is not null, so both move one node. lead is on 40 and trail on 20, still two steps apart.

  6. 1020304050leadtrail
    lead
    node 50
    trail
    node 30
    gap
    2

    6Both move again. lead is on 50, the last node, and trail is on 30. lead is still not null, so the loop goes on.

  7. 1020304050trail
    lead
    null
    trail
    node 40
    gap
    2
    moves in all
    8

    7Both move once more. lead steps past 50 and becomes null, and trail moves onto 40. The loop test lead != null now fails.

  8. 1020304050trail
    lead
    null
    trail
    node 40
    gap
    2
    answer
    node 40

    8We return trail. It is two steps behind a pointer that has just left the list, so it is the 2nd node from the end, 40.

Let us read the key frames back. In the third frame the first loop has finished and lead is on 30, two steps from the head. In the fourth, trail starts on 10, and the gap of two is set up. From then on, each frame moves both by one, and the gap in the panel never changes.

The seventh frame is the one that trips people up, so look at it closely. lead was on 50, the last node, in the sixth frame, and the loop still ran once more, because lead was not yet null. That last move takes lead off the end and brings trail from 30 to 40. Counting moves, lead made 5 and trail made 3, 8 in all, the same total as the brute force, but in a single walk along the list.

6The complete Java program

Here is the whole program. It has a small Node class, the nthFromEnd method, a build helper that makes a list from values, and a show helper that prints a node's value or null. main asks for the 2nd, the 1st and the 5th node from the end, then asks for the 6th, which does not exist, and finally uses an empty list.

Java
public class NthFromEnd {
static class Node {
int val;
Node next;
Node(int val, Node next) { this.val = val; this.next = next; }
}
// Returns the nth node from the end (n = 1 is the last node), or null if the list is shorter.
static Node nthFromEnd(Node head, int n) {
Node lead = head;
for (int i = 0; i < n; i++) { // move lead n nodes ahead
if (lead == null) return null; // fewer than n nodes
lead = lead.next;
}
Node trail = head;
while (lead != null) { // keep the gap of n until lead falls off
lead = lead.next;
trail = trail.next;
}
return trail;
}
static Node build(int... values) {
Node head = null;
for (int i = values.length - 1; i >= 0; i--) head = new Node(values[i], head);
return head;
}
static String show(Node node) {
return node == null ? "null" : String.valueOf(node.val);
}
public static void main(String[] args) {
Node list = build(10, 20, 30, 40, 50);
System.out.println(show(nthFromEnd(list, 2))); // 40
System.out.println(show(nthFromEnd(list, 1))); // 50
System.out.println(show(nthFromEnd(list, 5))); // 10
System.out.println(show(nthFromEnd(list, 6))); // null
System.out.println(show(nthFromEnd(null, 1))); // null
}
}

Let us read nthFromEnd in the order it runs. lead starts on head. The for loop runs n times. Inside it, the first thing we do is check whether lead is null, because if we have run out of nodes before taking n steps, the list is too short and the answer is null. Only then do we move lead forward. The order of those two lines matters: moving first and checking afterwards would wrongly reject a list of exactly n nodes.

When the for loop ends, lead is n steps ahead. We set trail to head, so the gap is exactly n. The while loop moves both one step at a time for as long as lead is not null. When lead becomes null, trail is the node we want, and we return it.

The helpers only make the program runnable. build goes through the values from the back, putting each new node in front of the list made so far, so the list ends up in the order the values were given. show prints the node's value, or the word null when there is no node, which keeps main from failing on the short and empty cases. So main prints 40, 50, 10, null and null.

7How much it costs, and the cases at the edges

Let us count on the example first. lead made 5 moves and trail made 3, so the method did 8 pointer moves and a few comparisons. For a list of L nodes, lead always makes L moves, if the list is long enough, and trail makes L - n, so the time is O(L). We keep two references whatever the length, so the extra space is O(1).

Is the one-pass version faster than counting? In the number of moves, no, as our count shows: both make 8. Its real advantages are that it walks the list once, which matters for a stream, and that it shows the gap technique, which is what the interviewer is checking. It is fair, and honest, to say that in an interview.

Comparing the ways to find the nth node from the end
ApproachTimeExtra spaceWalks the list
Count the length, then walk length - n stepsO(L)O(1)twice
Copy the nodes into an ArrayList and index itO(L)O(L)once
Push the nodes on a stack and pop n timesO(L)O(L)once
Two pointers with a gap of nO(L)O(1)once

The edge cases are handled by the two loops. An empty list returns null at the very first check, because lead is null before any step. When n equals the length, as with n = 5, the second loop never runs and the head is returned. When n is larger than the length, as with n = 6, the first loop finds lead null on its sixth step and returns null.

One case has no sensible answer, n of 0 or less. With n = 0 our method would skip the first loop and return the null after the last node, so in production code we would reject it with an IllegalArgumentException before starting.

8Follow-up questions

How do you remove the nth node from the end instead of returning it?

To remove a node we must change the next of the node before it, so trail has to stop one node earlier. We keep a gap of n + 1 instead of n. A dummy node, a spare node placed in front of the head, makes this uniform: start both pointers on the dummy, move lead n + 1 steps, then move both until lead is null, and set trail.next = trail.next.next. Returning dummy.next handles the case where the head itself is removed, which would otherwise need its own code.

How would you find the middle node in one pass?

With the same two references but a difference in speed instead of a fixed gap. slow moves one node per step and fast moves two. When fast reaches the end, slow has covered half the distance, so it is in the middle. For our list of five nodes, slow stops on 30. For an even length, the exact loop test on fast decides whether slow stops on the first or the second of the two middle nodes, so it is worth agreeing which one is wanted.

Could you do it with recursion?

Yes. A recursive method walks to the end first and counts on the way back: the call on the last node returns 1, the call on the node before it returns 2, and so on, and the call that receives n remembers its node. It is a nice exercise, but every node adds a waiting call on the stack, so it uses O(L) space and can overflow on a long list. The two pointer loop does the same job in O(1) space.

9Conclusion

We found the nth node from the end by sending a lead pointer n nodes ahead and then moving it and a trail pointer together until lead fell off the end, so trail stopped exactly n nodes from the end. It is one pass, O(L) time and O(1) space, and short lists are caught in the first loop. The clue to remember is a position measured from the end of a list you can only walk forwards: carry the distance with you as a fixed gap between two pointers.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the convention first: n = 1 means the last node, I return the node itself, and if the list has fewer than n nodes, or is empty, I return null.

Then, if they want more

The simple solution counts the length in one walk and then walks length minus n steps from the head; that is O(L) time and O(1) space, but it walks the list twice and needs the length. To do it in one pass, I use two pointers with a fixed gap.

I move a lead pointer n nodes ahead of the head, checking before each step that lead is not null, so a short list returns null. Then I start a trail pointer at the head and move both one step at a time while lead is not null.

Because the gap stays n, when lead steps past the last node, trail is exactly n nodes from the end, counting the last node as one. I stop when lead is null, not when it is on the last node, because stopping one step early would give the node one further back. It is O(L) time and O(1) space.

If the list has exactly n nodes, the second loop never runs and I return the head.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 26 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Find the nth node from the end of a linked list.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-nth-node-from-the-end-of-a-linked-list-307cbd/