Nth Node From End
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
Single element
1st from end is last element
2nd from end is 40
5th from end is first
Single
Algorithm Flow
Solution Approach
Return the element at index arr.length - n, with bounds checking.
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
class Solution {
public int solution(int[] nums, int n) {
return nums[nums.length-n];
}
}Related Linked List Challenges
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
