703156. Find the left over element
Easy
Find the Left Over Element
Summary
This problem requires you to find the leftover element in an array. The array is sorted, and one element is missing. Your task is to write a program that finds this missing element.
Detailed Explanation
The given array is already sorted. We can solve this problem by iterating through the array and comparing each element with its previous and next elements. If we find any pair of adjacent elements which have different values, then the middle element in that range will be the missing one.
Here's a step-by-step breakdown:
- Initialize two pointers,
startandend, to the beginning and end of the array. - Compare the elements at the
startandendindices. - If the difference between these elements is greater than 1, then the missing element must be in this range.
- Move the pointer that points to the smaller element towards the other pointer until the difference becomes 1 or less.
- The middle element of this range will be the missing one.
Time complexity: O(n) Space complexity: O(1)
Optimized Solutions
Java
public class Main {
public static int findMissingElement(int[] arr) {
if (arr.length < 2) return -1;
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int diff = Math.abs(arr[start] - arr[end]);
if (diff > 1) {
if ((arr[start + 1] - arr[start]) == 1)
return arr[start] + 1;
else if ((arr[end] - arr[end - 1]) == 1)
return arr[end] - 1;
start++;
end--;
} else {
if (diff == 0) return -1; // duplicate elements
if (start == end) return arr[start]; // single element array
start++;
end--;
}
}
return -1;
}
}