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