Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 141 · Fast & Slow Pointers

Linked List Cycle

LeetCode 141 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Floyd: fast meets slow ⇔ cycle.

సులభంHash TableLinked ListTwo PointersFloyd's Cycle Finding Algorithm
LeetCode లో తెరవండి ↗

నేను Linked List Cycle (LeetCode 141) ను ఇలా పరిష్కరించాను — Fast & Slow Pointers ప్యాటర్న్‌లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

Send a slow pointer one step and a fast pointer two steps. If there is a loop, the fast one eventually laps the slow one and they meet; if not, the fast pointer reaches the end.

Approach

  1. 1

    slow and fast start at head.

  2. 2

    Advance slow by 1 and fast by 2.

  3. 3

    Equal → cycle; fast hits None → no cycle.

నేను ఎలా పరిష్కరించాను

Floyd's cycle detectionPythonO(n) time · O(1) space
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow = head
        fast = head
        while fast and fast.next!=None:
            slow = slow.next
            fast = fast.next.next
            if slow==fast:
                return True
        return False
స్టెప్-త్రూ లోడ్ అవుతోంది…

Linked List Cycle — తరచూ అడిగే ప్రశ్నలు

Linked List Cycle వెనుక ఉన్న intuition ఏమిటి?

Send a slow pointer one step and a fast pointer two steps. If there is a loop, the fast one eventually laps the slow one and they meet; if not, the fast pointer reaches the end.

Linked List Cycle (LeetCode 141) ను ఎలా పరిష్కరించాలి?

1. slow and fast start at head. 2. Advance slow by 1 and fast by 2. 3. Equal → cycle; fast hits None → no cycle.

Linked List Cycle యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(1). (Accepted approach: Floyd's cycle detection.)

Linked List Cycle లో సాధారణ పొరపాట్లు ఏమిటి?

Compare nodes (identity), not values.