โ† Goldman Sachs questions

Find middle and Nth last element of linked list

Filed under Goldman Sachs

Free read 3 of 3

Confirm 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

  1. Confirm whether the length of the linked list is known in advance and how even-length middle selection is handled.

Solution

O(N) time, O(1) space

Python
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.