LeetCode Blind 75 in Swift: Solving the "Find Minimum in Rotated Sorted Array" Problem

Problem: Find Minimum in Rotated Sorted Array

The Find Minimum in Rotated Sorted Array problem asks you to find the minimum element in a rotated sorted array of unique elements.

Example:

Input: nums = [3, 4, 5, 1, 2]
Output: 1
Explanation: The minimum value is 1.
        

Swift Solution

class Solution {
    func findMin(_ nums: [Int]) -> Int {
        var left = 0
        var right = nums.count - 1

        while left < right {
            let mid = (left + right) / 2
            if nums[mid] > nums[right] {
                left = mid + 1
            } else {
                right = mid
            }
        }
        
        return nums[left]
    }
}

let solution = Solution()
let nums = [3, 4, 5, 1, 2]
let result = solution.findMin(nums)
print(result) // Output: 1
        

Explanation

This problem can be solved efficiently using binary search. The rotated sorted array has two sorted halves. By comparing the middle element with the rightmost element, we can determine which half contains the minimum. We adjust the search range accordingly until we find the minimum element.

Comments