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].