20. Find Only Repetitive Element from 1 to n-1
The problem can be found at the following link: Question Link
Problem Description
Given an array arr[] of size n, filled with numbers from 1 to n-1 in random order. The array has only one repetitive element. Your task is to find this repeating element.
It is guaranteed that there is exactly one repeating element.
Examples
Example 1:
Input:
arr[] = [1, 3, 2, 3, 4]Output:
3Explanation:
The number 3 is repeated in the array.
Example 2:
Input:
arr[] = [1, 5, 1, 2, 3, 4]Output:
1Explanation:
The number 1 appears twice.
Example 3:
Input:
arr[] = [1, 1]Output:
1Explanation:
The only possible value 1 is repeated.
Constraints:
$(2 \leq \text{arr.size()} \leq 10^5)$
$(1 \leq \text{arr}[i] \leq n - 1)$
My Approach
Floyd’s Tortoise and Hare (Cycle Detection Algorithm)
The problem of finding a duplicate number in an array can be visualized as detecting a cycle in a linked list. Here's the intuition:
Each element in the array represents a "pointer" to the next index, i.e.,
arr[i]points toarr[arr[i]].Because there's one number that appears twice, it effectively creates a cycle in this virtual "linked list".
Our goal is to find the entry point of this cycle, which corresponds to the repeated number.
To do this, we apply Floyd’s Cycle Detection Algorithm, commonly known as the Tortoise and Hare algorithm:
Algorithm Steps:
Phase 1 – Finding the Intersection Point:
Initialize two pointers,
slowandfast, both starting at the first index.Move
slowone step at a time (slow = arr[slow]).Move
fasttwo steps at a time (fast = arr[arr[fast]]).Eventually, the two pointers will meet inside the cycle.
Phase 2 – Finding the Entrance to the Cycle (Duplicate):
Reinitialize one pointer (
fast) to the start of the array.Move both
slowandfastone step at a time.The point where they meet again is the duplicate number (the cycle's entry point).
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), since each phase (finding intersection and finding entrance) takes linear time.
Expected Auxiliary Space Complexity: O(1), as only a constant number of pointers are used.
Code (C++)
class Solution {
public:
int findDuplicate(vector<int>& a) {
int s = a[0], f = a[0];
do {
s = a[s];
f = a[a[f]];
} while (s != f);
f = a[0];
while (s != f) {
s = a[s];
f = a[f];
}
return s;
}
};Code (Java)
class Solution {
public int findDuplicate(int[] a) {
int s = a[0], f = a[0];
do {
s = a[s];
f = a[a[f]];
} while (s != f);
f = a[0];
while (s != f) {
s = a[s];
f = a[f];
}
return s;
}
}Code (Python)
class Solution:
def findDuplicate(self, a):
s = f = a[0]
while True:
s = a[s]
f = a[a[f]]
if s == f: break
f = a[0]
while s != f:
s = a[s]
f = a[f]
return sContribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated