Problem
Finding the Minimum Value in a Valley-Shaped Array
Examples
Example 1:
Input: arr = [12, 8, 4, 2, 3, 10];
Output: 3
Solution
Method 1 - Binary Search
Use a binary search to efficiently find the trough element (the minimum value) in the array.
Steps:
- Initialize two pointers,
left
andright
, at the beginning and end of the array. - Perform a binary search:
- Compute the middle index
mid
. - Compare
arr[mid]
witharr[mid + 1]
. - If
arr[mid]
is smaller thanarr[mid + 1]
, it indicates that the trough is on the left half (including mid). - Otherwise, the trough is on the right half (excluding mid).
- Compute the middle index
- Continue until
left
meetsright
. The positionleft
orright
will point to the trough element or the minimum value in the array.
Code
Java
class Solution {
public int findMinInValleyArray(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] < arr[mid + 1]) {
// Trough must be in the left half, including mid
right = mid;
} else {
// Trough must be in the right half, excluding mid
left = mid + 1;
}
}
// Left (or right) will be the index of the trough element
return left;
}
}
Python
class Solution:
def findMaxInBitonicArray(self, arr: List[int]) -> int:
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] > arr[mid + 1]:
# Peak must be in the left half, including mid
right = mid
else:
# Peak must be in the right half, excluding mid
left = mid + 1
# Left (or right) will be the index of the peak element
return left
Complexity
- ⏰ Time complexity:
O(log n)
- 🧺 Space complexity:
O(1)