Hello Guys! This is day 95 and we are going to solve another problem using Tortoise And Hare Algorithm. In case you don't know it, check out my previous article on it.
Analyzing the Middle of a Linked List
The problem at hand involves finding the middle node of a linked list. It's a famous question often encountered in coding interviews. Let's break down the problem, understand the approach, and perform a dry run with an example to understand it better
Problem Statement: Middle of a Linked List
You are given a singly linked list, and you need to find the middle node of the list. If the list has an even number of nodes, return the second middle node.
The Approach
Before diving into the code, let's understand the intuition behind the approach.
We can use a classic technique known as the "two-pointer" or "tortoise and hare" approach to efficiently find the middle of the linked list.
We initialize two pointers,
slowandfast, both initially pointing to the head of the list.The
slowpointer moves one step at a time, while thefastpointer moves two steps at a time.When the
fastpointer reaches the end of the list (i.e.,fastorfast->nextbecomesnullptr), theslowpointer will be at the middle of the list.This is because the
fastpointer covers twice the distance in the same time it takes for theslowpointer to traverse the list once.
Example Dry Run
Let's perform a dry run with an example linked list to see how this approach works.
Consider the linked list: 1 -> 2 -> 3 -> 4 -> 5
Initially, both
slowandfastpoint to the head, which is1.In the first iteration,
slowmoves to2, andfastmoves to3.In the second iteration,
slowmoves to3, andfastmoves to5.In the third iteration,
slowstays to3, andfastreaches the end of the list, which isnullptr.Since
fastis nownullptr, we stop the loop, and theslowpointer points to the middle node, which is3.
The Code
Here's the code to find the middle node of a linked list:
ListNode* middleNode(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
Time Complexity: O(N)
Space Complexity: O(1)
Top comments (0)