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.