Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 287 · Cyclic Sort / Index Marking

Find the Duplicate Number

LeetCode 287 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Floyd's cycle detection on index → value pointers.

మధ్యస్థంArrayTwo PointersBinary SearchBit ManipulationPigeonhole Principle
LeetCode లో తెరవండి ↗

నేను Find the Duplicate Number (LeetCode 287) ను ఇలా పరిష్కరించాను — Cyclic Sort / Index Marking ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

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

Intuition

Treat the array as a function i → nums[i]. Because values are in 1..n with one repeat, following the pointers must enter a cycle, and the cycle's entrance is the duplicate. Floyd's tortoise and hare finds it without extra memory or modifying the array.

Approach

  1. 1

    Phase 1: slow = nums[slow], fast = nums[nums[fast]] until they meet.

  2. 2

    Phase 2: reset one pointer to the start.

  3. 3

    Move both one step at a time; they meet at the cycle entrance — the duplicate.

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

Floyd's tortoise and harePythonO(n) time · O(1) space
class Solution:
    def findDuplicate(self, nums):
        slow = nums[0]
        fast = nums[0]
        while True:  # do ... while
            slow = nums[slow]
            fast = nums[nums[fast]]
            if slow == fast:
                break
        fast = nums[0]
        while slow != fast:
            fast = nums[fast]
            slow = nums[slow]
        return slow
స్టెప్-త్రూ లోడ్ అవుతోంది…

Find the Duplicate Number — తరచూ అడిగే ప్రశ్నలు

Find the Duplicate Number వెనుక ఉన్న intuition ఏమిటి?

Treat the array as a function i → nums[i]. Because values are in 1..n with one repeat, following the pointers must enter a cycle, and the cycle's entrance is the duplicate. Floyd's tortoise and hare finds it without extra memory or modifying the array.

Find the Duplicate Number (LeetCode 287) ను ఎలా పరిష్కరించాలి?

1. Phase 1: slow = nums[slow], fast = nums[nums[fast]] until they meet. 2. Phase 2: reset one pointer to the start. 3. Move both one step at a time; they meet at the cycle entrance — the duplicate.

Find the Duplicate Number యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(1). (Accepted approach: Floyd's tortoise and hare.)

Find the Duplicate Number లో సాధారణ పొరపాట్లు ఏమిటి?

The 'do … while' first step matters: both start at nums[0].