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.