Find Minimum in Rotated Sorted Array

The "Find Minimum in Rotated Sorted Array" is a popular interview question that tests a candidate's problem-solving skills.

Asked in SDE interviews by Morgan Stanley, Amazon, Microsoft, Samsung, Adobe, and many more.

A rotated sorted array is an array rotated by k positions or rotated between 1 to n times.

The task is to find the minimum element in the array in Log(n) time.

For example:

Approach 1: Linear Search

The simplest approach is to perform a linear search through the array to find the minimum element. The time complexity of this approach is O(n), where n is the size of the array. This approach is straightforward but not efficient enough for large arrays.

Python code of the linear search:

Output:

Find Minimum in Rotated Sorted Array

Approach 2: Binary Search

A more efficient approach is to utilize the properties of a rotated sorted array and apply binary search to find the minimum element.

The algorithm can be summarized as follows:

  1. Initialize two pointers, 'low' and 'high', pointing to the start and end of the array, respectively.
  2. Check if the array is already sorted (i.e., the element at the low index is less than or equal to that at the high index). If true, the minimum element is at the low index, and we can return it.
  3. Calculate the mid index as (low + high) // 2 and store the element at that index.
  4. Compare the mid element with the elements at the low and high indices:
  5. If the mid element is greater than the element at the high index, the minimum element lies in the right half of the array. Move the 'low' pointer to mid + 1.
  6. Otherwise, the minimum element lies in the left half of the array. Move the 'high' pointer to the mid.
  7. Repeat steps 2-4 until the 'low' and 'high' pointers become equal, indicating that the minimum element has been found.

Python Implementation to Find the Minimum Element in Rotated Sorted Array:

Output:

Find Minimum in Rotated Sorted Array

Time complexity = O(log n), where n is the size of the array.

Binary search allows us to efficiently discard half of the array in each iteration, resulting in a faster solution.

C++ Implementation to Find the Minimum Element in Rotated Sorted Array:

Output:

Find Minimum in Rotated Sorted Array

C Implementation to Find the Minimum Element in Rotated Sorted Array:

Output:

Find Minimum in Rotated Sorted Array

The time complexity of this approach is also O(log n), and it offers an optimized solution for finding the minimum element in a rotated sorted array.

CONCLUSION:

In conclusion, understanding the concepts behind a rotated sorted array and utilizing efficient algorithms such as binary search can greatly improve the performance of finding the minimum element in this type of array. Being familiar with these approaches will help candidates tackle similar interview questions and showcase their problem-solving abilities to potential employers.






Latest Courses