703327. Element with left side smaller and right side greater
Element with left side smaller and right side greater
Summary
Given an unsorted array, find the element that has a smaller value on its left side and a greater value on its right side. This problem involves searching for an element in an array while maintaining a balance between left and right sides.
Detailed Explanation
To solve this problem, we can iterate through the array from both ends (left and right). We maintain two pointers, i and j, initially set to 0 and n-1, where n is the length of the array.
We compare the values at i and j. If arr[i] < arr[j], we move the left pointer to the right until we find a pair that satisfies the condition. If not, we move the right pointer to the left.
Once we find such an element, we return it as our answer.
Here's a step-by-step breakdown of the solution:
- Initialize two pointers
iandjto 0 andn-1, respectively. - Compare
arr[i]andarr[j]. Ifarr[i] < arr[j], move the left pointerito the right until you find a pair that satisfies the condition. - If not, move the right pointer
jto the left until you find a pair that satisfies the condition. - Return the element at index
(i + j) / 2as our answer.
The time complexity of this solution is O(n), where n is the length of the array. The space complexity is O(1).
Optimized Solutions
Java
public int findElement(int[] arr) {
int i = 0, j = arr.length - 1;
while (i < j) {
if (arr[i] < arr[j]) {
i++;
} else {
j--;
}
}
return arr[(i + j) / 2];
}