Leetcode 2095: Delete the Middle Node of a Linked List

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

You are given the head of a linked list. Your task is to remove the middle node from the linked list and return the modified list. The middle node is defined as the ⌊n / 2⌋th node, where n is the number of nodes in the list, using 0-based indexing.
Problem
Approach
Steps
Complexity
Input: The input consists of a linked list where each node has a value and a pointer to the next node. The linked list has at least one node.
Example: head = [4, 8, 6, 2, 7, 3]
Constraints:
• The number of nodes in the list is in the range [1, 10^5].
• 1 <= Node.val <= 10^5
Output: Return the linked list after removing the middle node. The list should be modified in place.
Example: Output: [4, 8, 2, 7, 3]
Constraints:
Goal: The goal is to remove the middle node from the linked list and return the modified list.
Steps:
• Use two pointers: one slow and one fast.
• Move the fast pointer two steps at a time and the slow pointer one step at a time.
• When the fast pointer reaches the end, the slow pointer will be at the middle.
• Remove the middle node by linking the previous node of the slow pointer to the next node.
Goal: The problem ensures that the list has a valid number of nodes and the node values are within the specified range.
Steps:
• The list has at least one node.
• The number of nodes is between 1 and 10^5.
Assumptions:
• The linked list is not empty.
• The values in the list are distinct.
Input: Example 1: head = [4, 8, 6, 2, 7, 3]
Explanation: The list has 6 nodes. The middle node is 6 (index 2). After removing it, the list becomes [4, 8, 2, 7, 3].

Input: Example 2: head = [10, 20, 30, 40]
Explanation: The list has 4 nodes. The middle node is 30 (index 2). After removing it, the list becomes [10, 20, 40].

Input: Example 3: head = [5, 3]
Explanation: The list has 2 nodes. The middle node is 3 (index 1). After removing it, the list becomes [5].

Link to LeetCode Lab


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