Find Minimum in Rotated Sorted Array
Public Module RotatedArrayMinFinder ' Finds the minimum element in a rotated sorted array. ' The array may contain duplicates. Public Function FindMin(ByVal nums() As Integer) As Integer If nums Is Nothing OrElse nums.Length = 0 Then Throw New ArgumentException("Input array canno...
This algorithm finds the minimum element in a rotated sorted array, which is an array that was originally sorted in ascending order and then rotated at some pivot point. The array might contain duplicate elements. It emp...
The `FindMin` function uses a binary search approach adapted for rotated sorted arrays, specifically handling duplicates. The core idea is to compare the middle element (`nums(mid)`) with the rightmost element (`nums(right)`). If `nums(mid) > nums(right)`, it implies that the rotation point (and thus the minimum element) lies in the right half of the array (`[mid + 1, right]`). If `nums(mid) < nums(right)`, the minimum element must be in the left half, including `mid` (`[left, mid]`). The most challenging scenario arises when `nums(mid) == nums(right)`. In this case, we cannot definitively determine which half contains the minimum. To resolve this, we safely discard the rightmost element by decrementing `right`. This is because if `nums(right)` is the minimum, `nums(mid)` is also a candidate, and we will eventually find it. If `nums(right)` is not the minimum, discarding it does not lose the true minimum. The loop invariant is that the minimum element is always contained within the `[left, right]` range. The time complexity is O(log n) on average, but degrades to O(n) in the worst case where all elements are identical due to the duplicate handling. The space complexity is O(1) as it uses a constant amount of extra space.
Function FindMin(array): If array is empty, throw error. Set left = 0, right = length of array - 1. While left < right: Calculate mid = left + (right - left) / 2. If array[mid] > array[right]: Set left = mid + 1. Else If...