Skip to problem
←

Middle of the Linked List

Easy 0 attempts

You get the head of a singly linked list. Return the middle node. If the number of nodes is even, there are two middle positions; return the second of those (the one closer to the tail).

Return the node itself. The examples display the suffix beginning at that node.

Return the original node object without modifying any values or links. A newly allocated list with matching values is not the requested node. For a single-node list, return its head.

Function contract

Implement middleNode(head). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Return the original node at zero-based index floor(n / 2). Do not modify the list. The runner displays the suffix starting at that node.

Example 1

Input
head = [1,2,3,4,5]
Output
[3,4,5]

Example 2

Input
head = [1,2,3,4,5,6]
Output
[4,5,6]
Constraints
  • 1 to 100 nodes
  • 1 <= Node.val <= 100

Slow and Fast Pointers

Move slow one node and fast two nodes at each step. When fast reaches the end, slow has advanced floor(n / 2) positions, which selects the second middle for even lengths. Only references move; the list itself is unchanged.

javascript
function middleNode(head) {
  let slow = head, fast = head;
  while (fast && fast.next) { slow = slow.next; fast = fast.next.next; }
  return slow;
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript