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.