Middle of the Linked List
LeetCode 876 · সহজ · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Slow / fast pointers.
আমি Middle of the Linked List (LeetCode 876) এভাবে সমাধান করেছি — Basics প্যাটার্নের একটি সহজ প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Move one pointer a step at a time and another two steps at a time. When the fast pointer runs off the end, the slow one is in the middle.
Approach
- 1
slow = fast = head.
- 2
While fast and fast.next: slow one step, fast two.
- 3
Return slow (the second middle for even lengths).
আমি কীভাবে সমাধান করেছি
Tortoise and harePythonO(n) time · O(1) space
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow =fast= head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slowMiddle of the Linked List — সাধারণ প্রশ্ন
Middle of the Linked List-এর পেছনে intuition কী?
Move one pointer a step at a time and another two steps at a time. When the fast pointer runs off the end, the slow one is in the middle.
Middle of the Linked List (LeetCode 876) কীভাবে সমাধান করবেন?
1. slow = fast = head. 2. While fast and fast.next: slow one step, fast two. 3. Return slow (the second middle for even lengths).
Middle of the Linked List-এর time আর space complexity কত?
Time: O(n)। Space: O(1)। (Accepted approach: Tortoise and hare।)
Middle of the Linked List-এ সাধারণ ভুলগুলো কী?
The loop condition decides first vs second middle.