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.