Leetcode 876: Middle of the Linked List

grid47
grid47
Exploring patterns and algorithms
Aug 11, 2024 5 min read

You are given the head of a singly linked list. Your task is to find and return the middle node of the list. If there are two middle nodes, return the second one.
Problem
Approach
Steps
Complexity
Input: The input is a singly linked list with nodes containing integer values.
Example: Input: head = [1, 2, 3, 4, 5]
Constraints:
• 1 <= number of nodes <= 100
• 1 <= Node.val <= 100
Output: Return the middle node of the linked list. If the list has two middle nodes, return the second one.
Example: Output: [3, 4, 5]
Constraints:
• The output should be the list starting from the middle node.
Goal: The goal is to determine the middle node of the linked list using a two-pointer approach.
Steps:
• Use two pointers, 'slow' and 'fast'. Initialize both to the head of the list.
• Move the 'slow' pointer one step at a time, and the 'fast' pointer two steps at a time.
• When the 'fast' pointer reaches the end of the list, the 'slow' pointer will be at the middle node.
Goal: The solution must efficiently handle lists of varying lengths within the given constraints.
Steps:
• The list contains between 1 and 100 nodes.
• Each node contains an integer between 1 and 100.
Assumptions:
• The linked list is non-empty and contains at least one node.
• The linked list may have an even or odd number of nodes.
Input: Input: head = [1, 2, 3, 4, 5]
Explanation: The list has 5 nodes. The middle node is 3, so the output will be the sublist starting from node 3: [3, 4, 5].

Input: Input: head = [1, 2, 3, 4, 5, 6]
Explanation: The list has 6 nodes. The two middle nodes are 3 and 4, and since the second middle node should be returned, the output will be the sublist starting from node 4: [4, 5, 6].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus