Question

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:

  • [4,5,6,7,0,1,2] if it was rotated 4 times.
  • [0,1,2,4,5,6,7] if it was rotated 7 times.

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

Given the sorted rotated array nums of unique elements, return the minimum element of this array.

You must write an algorithm that runs in O(log n) time.

This is abinary_search question.

Idea

  • Use the regular binary search algorithm
  • The trick here is to identify what portion of the array we’re in
    • The array has a pivot point [4, 5, 6, 1, 2, 3], here the array is broken into an L and R portion
    • If we are in the left portion greater than the right most, search to the right
    • If we are in the right portion less than left most, search to the left
    • If our left pointer is < our right pointer, the array is sorted and we can return L which would be the minimum

Solution