Recursion

Min in a Rotated Sorted Array

Given a rotated sorted array arr, return the minimum value in the array.

Every element in the array is a unique integer.

Example:

arr = [9, 12, 14, 1, 4, 5, 7, 8]=> returns 1\notag \begin{align*} &\texttt{arr = [9, 12, 14, 1, 4, 5, 7, 8]}\\ &\texttt{=> returns 1} \end{align*}

Explanation: The element 1 is the minimum value in the array.

First Few Test Cases:

1. Recursion

The first thing to realize is the array has 2 parts. We'll call them "left" and "right":

It's hard to know where to start, so let's consider some random example to try and make progress. Say we pick this example:

In this case, our search should continue towards the left side of the array since that's where the smallest value "1" is. We can do this by searching between i and mid.

In general, whenever we find ourselves in the "right" part of the array, we want to continue searching towards the left.

The other case is if mid is in the "left" part of the array. In this case, we should search towards the right:

Here's the recursion, putting these two cases together:

How do we figure out if mid is in the "left" or "right" part of the array?

If mid is in the right part, then we'll have arr[mid] <= arr[j]:

If mid is in the left part, then we'll have arr[mid] > arr[j]:

Here's the recursion, filling this in:

It's important to confirm to yourself that these conditions work even in small cases like searching 3, 2, or 1 element, and searching in an unrotated array.

2. Base case

The recursion should keep going until the search interval has narrowed on one element.

3. Code

Here's the full code, combining the recursion and the base case:

Time Complexity O(logn)O(\log n)

Space Complexity O(logn)O(\log n) for the Call Stack.

You can make the above code iterative, like this:

Time Complexity O(logn)O(\log n)

Space Complexity O(1)O(1)

Here's an alternative solution that uses hijacking. It's slightly more efficient because it uses j = mid-1, eliminating elements faster. But it's a little harder to work through all the edge cases.

Mark as Completed:
Submits:
smallestElement
Test your code to get an output here!
smallestElement(
)
Test your code to get an output here!