Yes, you can use the first element as a pivot also. Just need to handle the scenario for non-rotated array at the start. I was also wondering why last element was used as a magic value but it seems that we can use the front or the back as a pivot for filtering.
from typing import List
def find_min_rotated(arr: List[int]) → int:
if arr[0] < arr[-1]:
return 0
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] >= arr[0]:
left = mid + 1
else:
right = mid
return left
public static int findMinRotated(List arr) {
// WRITE YOUR BRILLIANT CODE HERE
int left = 0;
int right = arr.size() - 1;
int mid = 0;
while(left <= right) {
mid = left + (right - left) / 2;
if (arr.get(mid) > arr.get(right)){
left = mid + 1;
} else {
right = mid - 1;
}
}
return mid;
}
You need to add a test case where boundary elt is in the left half of the array ([19,1,2,3,4]), otherwise next code passes (comparing to right pointer elt instead of end pointer):
function findMinRotated(arr) {
let start = 0
let end = arr.length - 1
let bound = -1
while (start <= end) {
let mid = Math.floor((start + end) / 2)
if (arr[mid] > arr[end]) {
start = mid + 1
} else {
end = mid - 1
}
bound = start
}
return bound;
}
comparing arr[mid] <= arr[-1] is what tripped me up. I was doing it with arr[right] and would always have 1 test case that failed. Anyone have a thorough explanation why we can’t use arr[right] in the equality comparison?
This comment can be confusing.
Instead of saying: // if <= last element, then belongs to lower half
Using: // // if <= minimum element, then belongs to lower half
The comment is strange “# if <= last element, then belongs to lower half”, but the last element (which belongs to the higher half) is just <= last element