876. Middle of the Linked List

876. Middle of the Linked List
Photo by insung yoon / Unsplash

Problem

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: head = [1,2,3,4,5] Output: [3,4,5] Explanation: The middle node of the list is node 3.

Example 2:

Input: head = [1,2,3,4,5,6] Output: [4,5,6] Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

Constraints:

  • The number of nodes in the list is in the range [1, 100].
  • 1 <= Node.val <= 100

Solution

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def middleNode(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        """
        We can do this with 2 loops, can we do it with just 1 loop?
        I am thinking 2 pointers
        First pointer is "fast", it travels at N speed
        Second pointer travels at N/2 speed
        So it only increments when pointer1 is > n/2 away 
        Because by definition the "middle" is half of the max length
        therefore the maxium the second pointer can travel is n / 2

        Alternatively we can view this a different way. The maximum speed pointer1 can travel is N
        the maximum speed pointer2 can travel is half of N, so n / 2
        Therefore we use a fast and slow approach
        """
        fast, slow = head, head
        while fast and fast.next:
            # slow will happen to be in the middle when fast can no longer run
            fast = fast.next.next
            slow = slow.next
        return slow
        
                

This is similar to the fast and slow problem:

141. Linked List Cycle
❤️ I love the algorithm used here! Problem Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the