153. Find Minimum in Rotated Sorted Array

Description

See https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/

Note that the array is assumed to have one element.

The solution must run in O(log n) time.

Notes

This is similar to question 33. Search in Rotated Sorted Array.

O(log n) time means that binary search should be used.

Solutions

My Solution

My idea was to modify the standard binary search algorithm so that the left pointer will point at the min value in the array.

If nums[left] <= nums[right] then the array is not rotated. So we can just return nums[left]. Example, given the array [1, 2, 3, 4, 5], nums[0] < nums[4], nums[0] (value 1) is the min value of the array.

If nums[left] > nums[right] then we are in a rotated array. So, we need to determine if the mid pointer is on the left or right of the rotation point.

If the mid pointer is to the left of the rotation point, then we need to look to the right of the rotation point for the min value. For example, given the array [4, 5, 6, 7, 8, 1, 2, 3], if the mid point is at index 3 (value 7) then we know the min value must be to the right. So, set the left pointer to mid + 1.

If the mid pointer is to the right of the rotation point, then there are two scenarios to consider:

  • The mid point is not on the rotation point. In this case the min value will be somewhere to the left of the mid point. For example, given the array [7, 8, 9, 10, 0, 1, 2, 3, 4, 5, 6], if mid point is at index 5 (value 1), then we are not at the rotation point, and there is still a value less than it to the left. So, set the right pointer to mid - 1.

  • The mid point is on the rotation point. This is the smallest value in the array, so return it.

Time Complexity: O(log n)

Space Complexity: O(1)

LeetCode Solution

See https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/solution/

Last updated