Code Logo

Nth Node From End

Published at25 Jul 2026
Operations Easy 1 views
Like0

Given an array representing a linked list and an integer n, return the value of the nth node from the end of the list. The last element is considered the 1st from the end, the second-to-last is the 2nd, and so on.

For example, in [1, 2, 3, 4, 5], the 1st node from the end is 5, the 2nd is 4, and the 3rd is 3. If n is larger than the array length, return 0. If the array is empty, return 0.

Finding the nth node from the end of a linked list is a classic interview problem that introduces the two-pointer technique with an offset. Move one pointer n steps ahead, then advance both pointers together. When the leading pointer reaches the end, the trailing pointer is at the nth node from the end.

In an array, this is simply index length - n (1-indexed from the end). But in a linked list, you cannot access by index — you must use the two-pointer technique, which runs in O(n) time with O(1) space. The technique works regardless of the list length and requires only a single traversal.

Edge cases include n = 1 (return the last element), n equal to the array length (return the first element), n larger than the array length (return 0), and an empty array (return 0). The solution must handle all these correctly.

Example Input & Output

Example 1
Input
[5],1
Output
5
Explanation

Single element

Example 2
Input
[1,2,3],1
Output
3
Explanation

1st from end is last element

Example 3
Input
[10,20,30,40,50],2
Output
40
Explanation

2nd from end is 40

Example 4
Input
[1,2,3,4,5],5
Output
1
Explanation

5th from end is first

Example 5
Input
[10],1
Output
10
Explanation

Single

Algorithm Flow

Recommendation Algorithm Flow for Nth Node From End

Solution Approach

Return the element at index arr.length - n, with bounds checking.

function solution(arr, n) {
  if (arr.length === 0 || n > arr.length) return 0;
  return arr[arr.length - n];
}

For the array version, compute the index as length - n (1-indexed from the end). Check that n is not larger than the array length and that the array is not empty — if either condition fails, return 0 as a sentinel value. Otherwise, return the element at the computed index.

For the linked list two-pointer version: advance a fast pointer n steps ahead, then move both fast and slow pointers together until fast reaches the end. Slow is now at the nth node from the end.

Time complexity is O(n), space complexity is O(1).

Best Answers

java
class Solution {
    public int solution(int[] nums, int n) {
        return nums[nums.length-n];
    }
}