Leetcode 287: Find the Duplicate Number

grid47
grid47
Exploring patterns and algorithms
Oct 9, 2024 5 min read

A series of numbers, with the duplicate gently glowing and standing out from the rest.
Solution to LeetCode 287: Find the Duplicate Number Problem

You are given an array nums of n + 1 integers where each integer is in the range [1, n]. The array contains exactly one duplicate number. Find and return this duplicate number without modifying the array and using constant extra space.
Problem
Approach
Steps
Complexity
Input: The input is an array `nums` containing `n + 1` integers. Each element is between 1 and `n` (inclusive).
Example: For example, `nums = [1, 2, 3, 4, 2]`.
Constraints:
• 1 <= n <= 10^5
• nums.length == n + 1
• 1 <= nums[i] <= n
• All integers in `nums` appear only once except for one duplicate number.
Output: Return the duplicate number found in the array.
Example: For `nums = [1, 2, 3, 4, 2]`, the output should be `2`.
Constraints:
• The solution must be performed without modifying the array and using constant extra space.
Goal: Find the duplicate number in the array using the given constraints.
Steps:
• We will use a cycle detection approach (Floyd's Tortoise and Hare algorithm) to detect the duplicate number.
• Initialize two pointers `slow` and `fast`. The slow pointer moves one step at a time, while the fast pointer moves two steps.
• When both pointers meet, we reset one pointer to the start and move both pointers one step at a time until they meet again. The meeting point will be the duplicate number.
Goal: The solution should work within the time and space constraints.
Steps:
• The array should not be modified.
• Constant extra space should be used.
Assumptions:
• There is exactly one duplicate number in the array.
• The input array meets the constraints of having `n + 1` elements, with values between 1 and `n`.
Input: For `nums = [1, 2, 3, 4, 2]`
Explanation: The duplicate number in the array is `2`, as it appears twice.

Input: For `nums = [5, 1, 3, 4, 5]`
Explanation: The duplicate number in the array is `5`, as it appears twice.

Input: For `nums = [6, 6, 6, 6, 6]`
Explanation: All the numbers in the array are the same, and the duplicate number is `6`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus