Intuition

  • Set left and right global variables with first and last element index. Start iterating and update mid based on left and right variables.

Code

function findMin(nums) {
    let left = 0;
    let right = nums.length - 1;
 
    while (left < right) {
        let mid = Math.floor((left + right) / 2);
 
        // If the mid element is greater than the rightmost element,
        // it means the minimum element is in the right half.
        if (nums[mid] > nums[right]) {
            left = mid + 1;
        } else {
            // Otherwise, the minimum element is in the left half or is the mid element.
            right = mid;
        }
    }
 
    // The final value of 'left' is the index of the minimum element.
    return nums[left];
}
 
// Example usage:
const rotatedArray = [4, 5, 6, 7, 0, 1, 2];
const minimumElement = findMin(rotatedArray);
console.log(minimumElement); // Output: 0