Algo-Sim › Linked Lists
Find the Duplicate Number
Medium · Linked Lists · step through it in Java, Python and C++ on your own input
Find the one repeated value in n + 1 numbers from 1..n without changing the array or using extra memory. Treat i → nums[i] as a linked list and find its cycle's entry with Floyd's pointers.
Problem
An array nums holds n + 1 integers, each between 1 and n, so some value must repeat. Exactly one value repeats, though it may appear more than twice. Return it without modifying nums, using only constant extra space.
Constraints
- 1 ≤ n ≤ 10⁵, nums.length = n + 1
- 1 ≤ nums[i] ≤ n
- Exactly one value repeats
- O(1) extra space; do not modify nums
Edge cases to test
- The duplicate appears many times:
[2, 2, 2, 2] - n = 1:
[1, 1] - The duplicate is n
Follow-up questions
- Why is it a linked list?
- Treat i → nums[i] as a next pointer. Values are 1..n so 0 is never pointed to, and the duplicate value is where two pointers enter the cycle.
- What else meets the O(1)-space, read-only rule?
- Binary search on the value: count how many numbers are ≤ mid (pigeonhole): O(n log n).
Solution
Java
public int findDuplicate(int[] nums) {
int slow = 0, fast = 0;
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
int entry = 0;
while (entry != slow) {
entry = nums[entry];
slow = nums[slow];
}
return entry;
}Python
def find_duplicate(nums):
slow = fast = 0
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
entry = 0
while entry != slow:
entry = nums[entry]
slow = nums[slow]
return entryC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findDuplicate(vector<int> &nums) {
int slow = 0, fast = 0;
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
int entry = 0;
while (entry != slow) {
entry = nums[entry];
slow = nums[slow];
}
return entry;
}
};
More Linked Lists problems
- Reverse Linked List (Easy)
- Reverse Linked List (Recursive) (Easy)
- Merge Two Sorted Lists (Easy)
- Middle of the Linked List (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle (Easy)
- Linked List Cycle II (Medium)
- Intersection of Two Linked Lists (Easy)
- Remove Nth Node From End of List (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Copy List with Random Pointer (Medium)
- Reverse Nodes in k-Group (Hard)