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

मैंने 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].