Hone logo
Hone
Problems

Find Minimum in Rotated Sorted Array II

You are given a sorted array that has been rotated at some pivot point. This means the array might look like [4, 5, 6, 7, 0, 1, 2] where the original sorted array was [0, 1, 2, 4, 5, 6, 7]. The challenge is to find the minimum element in this rotated array. This type of problem is common in scenarios where data is partitioned or searched in a decentralized or distributed manner.

Problem Description

Given an array nums of integers that was originally sorted in ascending order and then rotated at some unknown pivot point. The array may contain duplicate elements. Your task is to find and return the minimum element in this array.

The goal is to efficiently find the minimum element, ideally in logarithmic time complexity.

Key Requirements:

  • Identify the smallest element in the rotated sorted array.
  • Handle the presence of duplicate elements in the array.

Expected Behavior:

  • The function should return the single minimum value present in the array.

Edge Cases:

  • An array with only one element.
  • An array where no rotation has occurred (i.e., it's still fully sorted).
  • An array filled with duplicate elements.

Examples

Example 1:

Input: [1, 3, 5]
Output: 1
Explanation: The array is not rotated, so the minimum element is the first element.

Example 2:

Input: [2, 2, 2, 0, 1]
Output: 0
Explanation: The array is rotated, and the minimum element is 0. The duplicates don't prevent us from finding it.

Example 3:

Input: [3, 1, 3]
Output: 1
Explanation: The array is rotated, and the minimum element is 1. The presence of duplicates requires careful handling.

Example 4:

Input: [10, 1, 10, 10, 10]
Output: 1
Explanation: Duplicates can make it harder to determine the rotation point. The minimum is 1.

Constraints

  • 1 <= nums.length <= 5000
  • -5000 <= nums[i] <= 5000
  • The array nums was originally sorted in ascending order and then rotated.
  • The array may contain duplicate elements.

Notes

The presence of duplicates can make standard binary search approaches tricky. Consider how duplicates might affect the comparison logic when trying to narrow down the search space. An efficient solution would aim for a time complexity better than linear search.

Here's pseudocode for a binary search approach, which you'll need to adapt to handle duplicates:

function findMin(nums):
  left = 0
  right = length(nums) - 1

  while left < right:
    mid = floor((left + right) / 2)

    // Compare nums[mid] with nums[right]
    // If nums[mid] < nums[right], the minimum is in the left half (including mid)
    // If nums[mid] > nums[right], the minimum is in the right half (excluding mid)
    // If nums[mid] == nums[right], we can't be sure, so we might need to shrink the search space from the right

    // Update left or right based on comparison

  return nums[left] // or nums[right], as left and right will converge to the minimum index
Loading editor...
plaintext