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