Find Minimum in Rotated Sorted Array II

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

Problem Statement

Imagine we have an array of integers of length 'n' that is initially sorted in ascending order. This array is then subjected to multiple rotations, between 1 and n times. For instance, the array nums = [0, 1, 4, 4, 5, 6, 7] could be transformed into [4, 5, 6, 7, 0, 1, 4] after being rotated four times. With each rotation, the last element of the array moves to the front, shifting all other elements one position to the right. The challenge presented is to determine and return the smallest element in such a rotated and possibly duplicate-laden array efficiently, minimizing the number of operational steps needed to achieve this.

Examples

Example 1

Input:

nums = [1,3,5]

Output:

1

Example 2

Input:

nums = [2,2,2,0,1]

Output:

0

Constraints

  • n == nums.length
  • 1 <= n <= 5000
  • -5000 <= nums[i] <= 5000
  • nums is sorted and rotated between 1 and n times.

Approach and Intuition

To efficiently find the minimum element in a rotated sorted array that may include duplicates, we can leverage a modified binary search. Given the constraints and nature of the problem, here’s a systematic step-by-step approach:

  1. Initiate pointers: start (low) at 0 and end (high) at n-1 of the nums array.

  2. Enter a while loop that continues as long as low < high:

    • Calculate the midpoint mid using mid = low + (high - low) / 2.
    • If the element at mid is greater than the element at high, it implies the smallest value is in the right half of the array. Thus, set low = mid + 1.
    • If the element at mid is less than the element at high, it indicates the smallest value is in the left half or at mid. Hence, set high = mid.
    • If nums[mid] equals nums[high], there is an ambiguity due to duplicate values. Reduce the search space conservatively by decrementing high by one.
  3. After exiting the loop, the pointer low will point to the smallest element since the loop narrows down the search window to the point where low equals high.

Considering the array may contain duplicates, this approach is particularly beneficial as straightforward binary search would not suffice without modifications. The slight adjustment where we decrement high addresses cases where the middle element is the same as the end element, a scenario common in arrays with duplicates. This approach ensures the algorithm remains efficient and runs in logarithmic time complexity in the best and average case, making it suitable for the input size constraints provided.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    int getMinimum(vector<int>& numbers) {
        int start = 0, end = numbers.size() - 1;

        while (start < end) {
            int mid = start + (end - start) / 2;
            if (numbers[mid] < numbers[end])
                end = mid;
            else if (numbers[mid] > numbers[end])
                start = mid + 1;
            else
                end -= 1;
        }
        return numbers[start];
    }
};

This solution tackles the problem of finding the minimum element in a potentially duplicated, rotated sorted array using C++. The approach leverages a binary search technique but with modifications to handle duplicate values and the rotation of the array.

The function getMinimum operates as follows:

  1. Initialize two pointers: start at index 0 and end at the last index of the numbers vector.
  2. Execute a while loop that continues as long as start is less than end.
    • Calculate the midpoint (mid) of the current start and end.
    • Compare the element at the midpoint (numbers[mid]) with the element at end (numbers[end]):
      • If numbers[mid] is less than numbers[end], narrow the search to the left half by setting end to mid.
      • If numbers[mid] is greater than numbers[end], narrow the search to the right half by setting start to mid + 1.
      • If they are equal, decrement end by one to reduce the search space slowly, handling potential duplicates effectively.
  3. Once the loop exits, start should be at the smallest element's position. Return numbers[start].

This strategy efficiently finds the minimum value in the array, ensuring optimum performance even in cases where duplicates exist and the typical binary search might falter.

java
class Solution {
    public int getMinimum(int[] array) {
        int start = 0, end = array.length - 1;

        while (start < end) {
            int mid = start + (end - start) / 2;
            if (array[mid] < array[end]) end = mid;
            else if (array[mid] > array[end]) start = mid + 1;
            else end -= 1;
        }
        return array[start];
    }
}

This article explains how to solve the problem of finding the minimum element in a rotated sorted array that may contain duplicates using Java.

The provided Java solution implements a binary search strategy to efficiently find the minimum element. Here's an overview of the approach:

  • Initialize start to 0 and end to the last index of the array.
  • Use a while loop to continue searching as long as start is less than end.
  • Calculate the middle index mid between start and end.
  • Compare the middle element with the end element to decide if you need to search the left half or the right half of the array:
    • If the middle element is less than the end element, set end to mid.
    • If the middle element is greater than the end element, set start to mid + 1.
    • If they are equal, decrement end by one to narrow the search range without skipping the minimum element.
  • Once the loop terminates, the minimum element is at the index start.

By employing this method, you ensure that you deal efficiently with duplicates and potentially reduce the search space more strategically.

c
int getMinimum(int* array, int size) {
    int start = 0, end = size - 1;

    while (start < end) {
        int middle = start + (end - start) / 2;
        if (array[middle] < array[end])
            end = middle;
        else if (array[middle] > array[end])
            start = middle + 1;
        else
            end -= 1;
    }
    return array[start];
}

This summary addresses the problem of finding the minimum element in an array that has been rotated and might contain duplicates. You will implement this using the C programming language with the provided function getMinimum.

  • The function getMinimum takes two parameters:

    • array - a pointer to the first element of the array.
    • size - the number of elements in the array.
  • The function utilizes a binary search mechanism to efficiently find the minimum value in the rotated sorted array. The approach deals effectively with duplicates by adjusting the search space.

  • Here’s a breakdown of the logic:

    1. Initialize two pointers, start and end, to reference the beginning and end of the array respectively.
    2. Use a while loop to continue searching while start is less than end.
    3. Calculate the middle index of the current search interval.
    4. Compare the element at the middle index with the element at the end index:
      • If the middle element is less than the end element, adjust the end pointer to middle.
      • If the middle element is greater than the end element, adjust the start pointer to middle + 1.
      • If they are equal, decrement the end pointer by 1 to narrow the search interval.
    5. Once the loop concludes, the start index will point to the minimum element in the rotated array.

Implement this in your C code to effectively find the smallest element, even when the input array has duplicates and is rotated.

js
var minimum = function (array) {
    let start = 0,
        end = array.length - 1;

    while (start < end) {
        let mid = start + Math.floor((end - start) / 2);
        if (array[mid] < array[end]) end = mid;
        else if (array[mid] > array[end]) start = mid + 1;
        else end -= 1;
    }
    return array[start];
};

This Javascript implementation effectively solves the problem of finding the minimum element in a rotated sorted array which may contain duplicates. The code utilizes a binary search approach, optimizing the search process even when the array is rotated and duplicates are present.

  • In the function minimum, two pointers are initialized, start and end, representing the boundaries of the current search index within the array.
  • The while loop continues as long as start is less than end.
    • Calculate the middle index mid using the start and end.
    • Three conditions help to refine the search area:
      • If the element at the middle (array[mid]) is less than the element at end, modify end to be mid, narrowing the search to the left segment.
      • If the middle element is greater than the end element, move start to mid + 1, focusing on the right segment.
      • If the middle element equals the end element, decrement the end index to reduce redundancy without missing the minimum.
  • Once the loop finishes, array[start] holds the minimum value, which is returned as the result.

This code ensures efficiency even in scenarios with large arrays and maintains a low time complexity, ideal for cases where performance is critical.

python
class Solution:
    def findMinimum(self, arr: List[int]) -> int:
        left = 0
        right = len(arr) - 1
        while right > left:
            mid = left + (right - left) // 2
            if arr[mid] < arr[right]:
                right = mid
            elif arr[mid] > arr[right]:
                left = mid + 1
            else:
                right -= 1
        return arr[left]

Explore how to find the minimum element in a sorted, potentially rotated, array where the array may contain duplicates using Python. The provided method uses a binary search approach to efficiently locate the minimum element even when duplicates are present.

  • Initialize two pointers, left and right, at the start and end of the array respectively.
  • Continue to narrow down the search space by adjusting the left and right pointers until they converge:
    • Calculate the midpoint of the current search space.
    • Compare the middle element with the element at the right pointer:
      • If the middle element is less than the element at right, adjust the right pointer to mid.
      • If the middle element is greater than the element at right, adjust the left pointer to one position right of mid.
      • If they're equal, decrement the right pointer by one to skip over the duplicate.
  • Eventually, the left pointer points to the smallest element when right converges to left.

This technique makes it possible to handle scenarios where the smallest number might be a duplicate and ensures the solution remains efficient even in those cases.

Comments

No comments yet.