Grind 75 - 22 - Middle of the Linked List
Senthil E.
Gen AI/ML Engineer/LLMOps | Databricks 5x Certified, Google 3x Certified, Tensorflow and AWS ML Certified.
LeetCode Problem Number: 876
Difficulty Level: Easy
Question: 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.
Questions to be Asked to the Interviewer
Edge Cases for This Problem
Available Approaches to Solve this Problem
Approach to Solve this Problem
I'll use the second approach using slow and fast pointers as it is more efficient.
Algorithm and Data Structure:
class ListNode:
? ? def __init__(self, val=0, next=None):
? ? ? ? self.val = val
? ? ? ? self.next = next
def middleNode(head: ListNode) -> ListNode:
? ? slow = fast = head
? ? while fast and fast.next:
? ? ? ? slow = slow.next
? ? ? ? fast = fast.next.next
? ? return slow
Explain the Solution to a Non-Programmer
领英推荐
Code in Detail :
The idea is to keep moving the slow pointer one step at a time and the fast pointer two steps at a time. When the fast pointer reaches the end, the slow pointer will be at the middle of the linked list.
Pattern of this Problem
This problem falls under the pattern of using two pointers (in this case, "slow" and "fast" pointers) to traverse a data structure (linked list) at different speeds. This pattern is often useful when trying to locate specific elements or characteristics in a data structure, such as the middle element in this case.
Big O Notation:
Points to Remember to Solve this Problem in the Future
Code Line by Line with Some Sample Data
Suppose the linked list is 1 → 2 → 3 → 4 → 5.
Key Syntax Used in this Solution:
The next problem is