Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

153. Find Minimum in Rotated Sorted Array

ArrayBinary Search

Explanation

To find the minimum element in a rotated sorted array, we can utilize a modified binary search algorithm. The idea is to compare the middle element of the array with the first and last elements to determine which half of the array to discard. This way, we can focus on the unsorted half where the minimum element lies.

  1. Initialize two pointers, left and right, pointing to the start and end of the array respectively.
  2. Perform binary search until left and right converge, indicating that the minimum element has been found.
  3. At each step, compare the middle element with the first and last elements to determine which half is unsorted and update left or right accordingly.
  4. Return the element at the left index, which will be the minimum element.

Time complexity: O(log n) Space complexity: O(1)

class Solution {
    public int findMin(int[] nums) {
        int left = 0, right = nums.length - 1;
        
        while (left < right) {
            int mid = left + (right - left) / 2;
            
            if (nums[mid] < nums[right]) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        
        return nums[left];
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.