Find the Duplicate Number - Complete Solution Guide
Find the Duplicate Number is LeetCode problem 287, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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. Example 1: Input: nums = [1,3,4,2,2] Output: 2 Example 2: Input: nums = [3,1,3,4,2] Output: 3 Example 3: Input: nums = [3,3,3,3,3] Output: 3 Constraints: 1 <= n <= 10 5 nums.length == n + 1 1 <= nums[i] <= n All the in
Detailed Explanation
The problem requires finding a duplicate number within an array `nums` of size `n + 1`, where each number is within the range `[1, n]`. There is exactly one repeated number, and the goal is to identify this repeated number without modifying the original array and using only constant extra space.
Solution Approach
The provided solution uses Floyd's cycle-finding algorithm, also known as the tortoise and hare algorithm, to find the duplicate number. The array `nums` is treated as a linked list where `nums[i]` represents the next node from node `i`. Because there is a duplicate number, there will be a cycle in the linked list. The algorithm works in two phases: (1) find the meeting point of the slow and fast pointers, and (2) find the entry point of the cycle.
Step-by-Step Algorithm
- Step 1: Initialize two pointers, `slow` and `fast`, to the starting index 0.
- Step 2: Move `slow` one step at a time (`slow = nums[slow]`) and `fast` two steps at a time (`fast = nums[nums[fast]]`).
- Step 3: Continue moving the pointers until `slow` and `fast` meet. This guarantees they are in the cycle.
- Step 4: Reset `finder` pointer to the starting index 0.
- Step 5: Move both `finder` and `slow` one step at a time until they meet. The meeting point is the entry point of the cycle, which is the duplicate number.
- Step 6: Return the value of `finder` (or `slow`), which is the duplicate number.
Key Insights
- Insight 1: The problem can be modeled as a linked list cycle detection problem.
- Insight 2: Each number in the array can be seen as a pointer to another number in the array (index). The presence of a duplicate creates a cycle.
- Insight 3: Floyd's cycle-finding algorithm (tortoise and hare) is a suitable approach to detect and locate the cycle start, which corresponds to the duplicate number.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Array, Two Pointers, Binary Search, Bit Manipulation.
Companies
Asked at: Anduril, Citadel, Goldman Sachs, Google, IBM, Infosys, J.P. Morgan, Niantic, Nvidia, Zoho.