Coding Interview Questions | Middle of Linked List
January 3rd, 2024
Maximum Depth Problem Introduction:
This summary will talk about my solution to the middle of the linked list problem as seen on leetcode here.
How do you solve the Middle of the Linked List Problem in O(n) time?
Solution:
function middleNode(head: ListNode | null): ListNode | null {
let slow = head;
let fast = slow;
while (fast && fast.next) {
slow = slow!.next;
fast = fast.next.next;
}
return slow;
}
Middle Node Solution Summary:
Below is an analysis of the key components of the provided solution:
-
Two-Pointer Approach: The algorithm employs a two-pointer approach with
slow
andfast
pointers. Initially, both pointers are set to the head of the linked list. -
Traversal Criteria: The while loop continues as long as the
fast
pointer and its next node (fast.next
) are not null. This ensures that the traversal proceeds until the end of the linked list. -
Pointer Movement: In each iteration, the
slow
pointer moves one step (slow = slow!.next
), while thefast
pointer advances two steps (fast = fast.next.next
). This results in theslow
pointer reaching the middle when thefast
pointer reaches the end. -
Return Middle Node: The algorithm returns the node pointed to by the
slow
pointer, which corresponds to the middle node of the linked list.
Complexities
-
Time Complexity: The time complexity of the solution is
O(n)
, wheren
is the number of nodes in the linked list. The two-pointer approach allows traversing the list in a single pass. -
Space Complexity: The space complexity is
O(1)
as the algorithm uses a constant amount of extra space, regardless of the input size.