Find the Duplicate Number
LeetCode 287 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Floyd's cycle detection on index → value pointers.
আমি 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
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.
আমি কীভাবে সমাধান করেছি
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 slowFind 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].