MEDIUM NC#42 Linked List / Floyd's Algorithm
287. Find the Duplicate Number
๐ Problem
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and using only constant extra space.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Treat array as linked list where nums[i] points to nums[nums[i]]
- โ This creates a cycle because of duplicate
- โ Use Floyd's cycle detection (fast/slow pointers)
- โ When cycle found, find entrance (the duplicate)
- โ Time: O(n), Space: O(1)
๐ ๏ธ Hints & Pitfalls
Hints
- โขTreat array as linked list where nums[i] points to nums[nums[i]]
- โขThis creates a cycle because of duplicate
- โขUse Floyd's cycle detection (fast/slow pointers)
Common Pitfalls
- โขWhen cycle found, find entrance (the duplicate)
- โขTime: O(n), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
findDuplicate([1,3,4,2,2]); Expected:
2 Test Case 2
Not run Input:
findDuplicate([3,1,3,4,2]); Expected:
3 Test Case 3
Not run Input:
findDuplicate([3,3,3,3,3]); Expected:
3 ๐ Code Editor
๐ค Output