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,
slow
andfast
, both initially pointing to the head of the list.The
slow
pointer moves one step at a time, while thefast
pointer moves two steps at a time.When the
fast
pointer reaches the end of the list (i.e.,fast
orfast->next
becomesnullptr
), theslow
pointer will be at the middle of the list.This is because the
fast
pointer covers twice the distance in the same time it takes for theslow
pointer 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
slow
andfast
point to the head, which is1
.In the first iteration,
slow
moves to2
, andfast
moves to3
.In the second iteration,
slow
moves to3
, andfast
moves to5
.In the third iteration,
slow
stays to3
, andfast
reaches the end of the list, which isnullptr
.Since
fast
is nownullptr
, we stop the loop, and theslow
pointer 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)