878900. Find Only Repetitive Element from 1 to n-1
Here is the Markdown blog post for the problem:
Find Only Repetitive Element from 1 to n-1
Slug: find-repetitive-element-from-1-to-n-1 Difficulty: Easy Id: 878900 Topic Tags: two-pointer-algorithm, Arrays Company Tags: None
Summary
This problem is about finding the only repetitive element in an array of numbers from 1 to n-1. The key concept involved is the two-pointer algorithm.
Detailed Explanation
The given array contains elements from 1 to n-1. To solve this problem, we use the two-pointer algorithm. We initialize two pointers, one at the start and one at the end of the array. Then, we compare the values at these positions. If they are equal, it means that the element is repetitive and we return it.
Here's a step-by-step breakdown of the solution:
- Initialize two pointers,
startandend, to the start and end of the array respectively. - Compare the values at the positions pointed by
startandend. - If they are equal, return that element as it is repetitive.
- Move the pointer with the smaller value towards the other pointer until they point to the same element again.
- That element is the only repetitive element in the array.
The time complexity of this algorithm is O(n) where n is the number of elements in the array, and the space complexity is O(1).
Optimized Solutions
Java
public class Solution {
public int findRepetitiveElement(int[] arr) {
if (arr.length == 0) return -1;
int start = 0, end = arr.length - 1;
while (start < end) {
int mid = start + (end - start) / 2;
if (arr[mid] != arr[start]) {
start = mid + 1;
} else {
end = mid;
}
}
return arr[start];
}
}