Find Minimum in Rotated Sorted Array

Updated on 26 May, 2025
Find Minimum in Rotated Sorted Array header image

Problem Statement

Given an array of integers that has been sorted in ascending order and then rotated between 1 and n times, where n is the length of the array, the task is to find the minimum element of this array. Each integer in the array is unique. The rotation of the array means that elements from the end of the array are moved to the beginning, thus altering the order of elements while maintaining the overall sequence. The goal is to achieve the solution in logarithmic time complexity, specifically O(log n), which suggests that an optimized approach like binary search should be considered.

Examples

Example 1

Input:

nums = [3,4,5,1,2]

Output:

1

Explanation:

The original array was [1,2,3,4,5] rotated 3 times.

Example 2

Input:

nums = [4,5,6,7,0,1,2]

Output:

0

Explanation:

The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.

Example 3

Input:

nums = [11,13,15,17]

Output:

11

Explanation:

The original array was [11,13,15,17] and it was rotated 4 times.

Constraints

  • n == nums.length
  • 1 <= n <= 5000
  • -5000 <= nums[i] <= 5000
  • All the integers of nums are unique.
  • nums is sorted and rotated between 1 and n times.

Approach and Intuition

The key intuition to solve the problem efficiently lies in understanding how the rotation affects the sorted array and how to leverage this alteration to find the minimum element using binary search.

  1. Observe that in a rotated sorted array, the minimum element signifies a pivotal point where the order restarts from the smallest value. This results in two sorted subarrays within the main array.
  2. Initiate a binary search. Set two pointers, left starting at index 0 and right at index n-1 of the array.
  3. Calculate the midpoint mid and compare the elements at nums[mid] with nums[right].
    • If nums[mid] is greater than nums[right], it indicates that the minimum element is to the right of mid because the elements are still in descending order. Here, move the left pointer to mid + 1.
    • Else, move the right pointer to mid because you're either at the minimum element or it’s in the left half.
  4. This binary approach essentially narrows down to the smallest element by halving the search space every iteration, sticking to the O(log n) time complexity requirement.

Illustrations from Examples:

  • In the first example nums = [3,4,5,1,2], a direct comparison between the middle element (which is 5) and the right-most element (which is 2) immediately tells us that the minimum lies in the right half of the array.
  • The situation with nums = [11,13,15,17] where the array appears not to have a distinctive rotating point suggests no change, but treating it as rotated n times simplifies consistent application of the same binary search logic. Here since the array is always in non-decreasing order from any midpoint, our binary search will effectively home in on the first element.

This method is efficient and leverages the properties of a rotated array to minimize computational steps needed to find the minimum element.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    int findMinimum(vector<int>& array) {
        if (array.size() == 1) {
            return array[0];
        }

        int start = 0, end = array.size() - 1;

        if (array[end] > array[start]) {
            return array[start];
        }

        while (end >= start) {
            int middle = start + (end - start) / 2;

            if (array[middle] > array[middle + 1]) {
                return array[middle + 1];
            }

            if (array[middle - 1] > array[middle]) {
                return array[middle];
            }

            if (array[middle] > array[start]) {
                start = middle + 1;
            } else {
                end = middle - 1;
            }
        }

        return -1;
    }
};

This solution in C++ tackles the problem of finding the minimum element in a rotated sorted array without duplicates. Here's a detailed breakdown of how the function works:

  • Start by checking if the array has only one element. If that's the case, return that element immediately.
  • Initialize two pointers, start set to the beginning of the array and end set to the last element.
  • Verify if the array is not rotated (the last element is greater than the first). If so, the first element is the minimum.
  • Use a while loop to continue as long as end is not less than start. Inside the loop:
    1. Find the middle index of the current subsection of the array.
    2. Check if the element at the middle is greater than the next one. If true, the next element is the minimum, so return it.
    3. Check if the previous element is greater than the element at the middle. If this holds, the middle element is the smallest, hence return it.
    4. Decide the next section to analyse based on whether the middle element is greater than the first element. If true, adjust the start pointer to middle + 1, otherwise adjust the end pointer to middle - 1.
  • If no minimum is found during the iterations, return -1 indicating an error.

This approach effectively utilizes binary search principles, making it efficient with a time complexity of O(log n), where n is the number of elements in the input array.

java
class Solution {
    public int findMinimum(int[] arr) {
        if (arr.length == 1) {
            return arr[0];
        }

        int start = 0, end = arr.length - 1;
        
        if (arr[end] > arr[start]) {
            return arr[start];
        }

        while (end >= start) {
            int middle = start + (end - start) / 2;

            if (arr[middle] > arr[middle + 1]) {
                return arr[middle + 1];
            }

            if (arr[middle - 1] > arr[middle]) {
                return arr[middle];
            }

            if (arr[middle] > arr[0]) {
                start = middle + 1;
            } else {
                end = middle - 1;
            }
        }
        return Integer.MAX_VALUE;
    }
}

The provided Java solution aims to find the minimum element in a rotated sorted array. This method handles various scenarios effectively and includes a binary search mechanism to optimize the search process efficiently.

Start by checking if the array has only one element, in which case that single element is the smallest. If the last element of the array is greater than the first, the array isn't rotated, and the first element is the smallest. Use a binary search to find the point of rotation where the order breaks and determine the smallest value. The conditions inside the loop are designed to locate this point:

  • If the middle element is greater than the next element, then the next element is the minimum.
  • If the previous element to the middle one is greater than the middle element itself, then the middle element is the minimum.
  • Update the search boundaries (start and end) based on the value comparisons to narrow down the search area.

This method provides a time-efficient solution, operating with a time complexity of O(log n), making it perform well even with large arrays due to reduced number of comparisons required compared to a simple linear search.

c
int findMinimum(int* array, int length) {
    // Handle single element case directly.
    if (length == 1) {
        return array[0];
    }

    // Initiate pointers for binary search.
    int start = 0, end = length - 1;

    // Check if the array is not rotated.
    if (array[end] > array[start]) {
        return array[start];
    }

    // Implementing binary search.
    while (end >= start) {
        // Calculate mid index.
        int mid = start + (end - start) / 2;

        // Check if current mid is the point of change.
        if (array[mid] > array[mid + 1]) {
            return array[mid + 1];
        }

        // Check if element before mid is the smallest.
        if (mid > 0 && array[mid - 1] > array[mid]) {
            return array[mid];
        }

        // Decide the search bounds adjustment.
        if (array[mid] > array[start]) {
            start = mid + 1;
        } else {
            end = mid - 1;
        }
    }

    return -1;
}

The provided C code resolves the challenge of finding the minimum element in a potentially rotated sorted array. Utilizing an approach centered around the binary search technique, it efficiently minimizes the search space and offers a notable performance advantage, especially beneficial for large datasets.

The code operates as follows:

  • Initially checks if the array contains only a single element, returning it immediately if that is the case.
  • Proceeds to initialize pointers for start and end to conduct a binary search.
  • Directly returns the first element if the array is observed to be not rotated (i.e., the last element is greater than the first).
  • Utilizes a while loop to perform the binary search where:
    • The midpoint (mid) is recalculated in each iteration.
    • Checks if the current mid element and the next element are consecutive but appear in descending order, indicating a point of minimum transition.
    • Assesses the condition for a change point just before the mid element.
    • Adjusts the search bounds based on comparisons between the mid element and the start, effectively narrowing down the search to the probable half containing the minimum.

This method ensures that the operations required to find the minimum element, even in the rotated state, remain efficient with a time complexity of O(log n), optimizing both execution time and utilizations of resources.

js
var getMinimum = function (values) {
    if (values.length == 1) {
        return values[0];
    }

    let start = 0,
        end = values.length - 1;

    if (values[end] > values[start]) {
        return values[start];
    }

    while (end >= start) {
        let midpoint = start + Math.floor((end - start) / 2);

        if (values[midpoint] > values[midpoint + 1]) {
            return values[midpoint + 1];
        }

        if (values[midpoint - 1] > values[midpoint]) {
            return values[midpoint];
        }

        if (values[midpoint] > values[start]) {
            start = midpoint + 1;
        } else {
            end = midpoint - 1;
        }
    }

    return Number.MAX_VALUE;
};

The provided JavaScript function getMinimum efficiently finds the smallest element in a rotated sorted array using a binary search approach. Below is a breakdown of how the solution works:

  • Start by checking if the array has only one element, in which case return that element as the minimum since it's the sole value.
  • Initialize start and end pointers to reference the beginning and the last index of the array, respectively.
  • If the element at the end index is greater than the element at the start index, the array hasn't been rotated and the first element is the smallest.
  • Use a while loop to perform binary search: keep running as long as end is greater than or equal to start.
    • Calculate midpoint as the floor division of start and end to determine the middle index.
    • If the element right after midpoint is less than the value at midpoint, then the successor is the minimum.
    • If the value just before midpoint is greater than the value at midpoint, then the current midpoint value is the minimum.
    • Decide the next search space: if the element at midpoint is greater than the element at start, adjust start to midpoint + 1; otherwise, adjust end to midpoint - 1.
  • If the loop concludes without finding the minimum, return Number.MAX_VALUE as a default failure condition.

Make sure to correctly handle arrays with single and multiple elements, and also ensure proper adjustment of pointers based on the condition checks to avoid infinite loops. The function overall efficiently locates the minimum value with a time complexity of O(log n), making it well-suited for large arrays.

python
class Solution:
    def findMinimum(self, array: List[int]) -> int:
        # Check for a single element
        if len(array) == 1:
            return array[0]

        # Initializing pointers
        start = 0
        end = len(array) - 1

        # No rotation scenario
        if array[end] > array[start]:
            return array[start]

        # Using binary search to find the minimum
        while end >= start:
            # Calculate mid point
            mid = start + (end - start) // 2
            # Identify potential minimum following the mid point
            if array[mid] > array[mid + 1]:
                return array[mid + 1]
            # Identify potential minimum at the mid point
            if array[mid - 1] > array[mid]:
                return array[mid]

            # Adjusting the search range based on comparison with first element
            if array[mid] > array[start]:
                start = mid + 1
            else:
                end = mid - 1

This Python3 solution effectively finds the minimum element in a rotated sorted array. The approach employs a binary search technique that efficiently narrows down the possible location of the minimum element, providing a time complexity better suited for large datasets compared to a linear search.

Understand the implementation steps:

  1. If the array contains a single element, that element is immediately returned as it is the minimum by default.

  2. Initialize two pointers: start at the beginning of the array and end at the last index.

  3. If the array element at the end index is greater than the element at the start index, the array has not been rotated and the minimum element is at the start index.

  4. Enter a while loop that continues until the start pointer is not greater than the end pointer:

    • Calculate the midpoint mid of the current array segment.

    • Check if the element following the midpoint is less than the element at the midpoint; if true, then the element following the midpoint is the minimum.

    • Check if the element at the midpoint is less than its preceding element; if true, then the element at the midpoint is the minimum.

    • Based on the value at the midpoint relative to the start pointer, adjust the start and end pointers to either the right or left segment of the midpoint for further searching.

Follow this procedure to utilize the provided code effectively in determining the minimum element in a sorted array that has been rotated, ensuring an optimal solution path for such problems.

Comments

No comments yet.