Leetcode 287. Find the Duplicate Number
Given an array of integers nums
containing n + 1
integers where each integer is in the range [1, n]
inclusive. There is only one duplicate number in nums
, return this duplicate number.
You must solve the problem without modifying the array nums
and use only constant extra space.
n + 1
integers where each integer is in the range [1, n]
, the smallest array would have two elements (e.g., [1, 1]
).nullptr
or contains invalid elements?
We will use Floyd’s Tortoise and Hare (Cycle Detection) algorithm to solve this problem in O(n) time complexity and O(1) space complexity. The idea is to interpret the array indices and values as nodes and their next pointers in a linked list and find the cycle.
#include <vector>
#include <iostream>
class Solution {
public:
int findDuplicate(std::vector<int>& nums) {
int slow = nums[0];
int fast = nums[0];
// Phase 1: Detecting the cycle
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
// Phase 2: Finding the cycle entrance
slow = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
};
int main() {
Solution solution;
std::vector<int> nums = {1, 3, 4, 2, 2};
std::cout << "Duplicate number is: " << solution.findDuplicate(nums) << std::endl; // Output: 2
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?