Find middle and Nth last element of linked list
Filed under Goldman Sachs
Free read 3 of 3Confirm whether the length of the linked list is known in advance and how even-length middle selection is handled.
The question
Write a program to find the middle element and the Nth-to-last (from the end) element of a singly linked list.
Constraints
- Must traverse the linked list in optimal time complexity.
- Assume 1-based indexing for the Nth element from the end if applicable.
Examples
- Input
- List: 1 -> 2 -> 3 -> 4 -> 5, N = 2
- Output
- Middle: 3, Nth from end: 4
- Why
- Middle node is 3. The 2nd node from the end is 4.
Approach
Confirm whether the length of the linked list is known in advance and how even-length middle selection is handled.
Traverse the list fully to count total nodes, then traverse a second time to find the middle and Nth from the end.
Use the slow and fast pointer technique for the middle element in one pass. Use a two-pointer gap of N nodes for the Nth-to-last element in a single pass.
Empty list, single node list, and N greater than the total number of nodes.
Solution
O(N) time, O(1) space
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def find_middle_and_nth_from_end(head, n):
slow = fast = head
middle = None
# Find middle
while fast and fast.next:
slow = slow.next
fast = fast.next.next
middle = slow
# Find Nth from end
first = second = head
for _ in range(n):
if not first: return None, middle.val
first = first.next
while first:
first = first.next
second = second.next
return second.val, middle.val
Tips
- What they are testing: Test lists with an even number of elements, single-element lists, and edge cases where N equals the length of the list.
- Common mistake: Off-by-one errors when advancing the fast pointer in the two-pointer approach for Nth from the end.
Related Goldman Sachs questions
Collected from public candidate posts and coding forums. Updated Nov 2026.