This approach utilizes binary search to identify the smallest element in a rotated sorted array. The idea is based on the characteristics of the rotated array where at least one half of the array is always sorted. By comparing middle and right elements, we can decide whether the rotation point lies to the left or right of the middle element, effectively narrowing down the search space.
Time Complexity: O(log n) where n is the number of elements in the input array.
Space Complexity: O(1) as no extra space is used except for variables.
1function findMin(nums) {
2 let low = 0, high = nums.length - 1;
3 while (low < high) {
4 let mid = Math.floor(low + (high - low) / 2);
5 if (nums[mid] > nums[high]) {
6 low = mid + 1;
7 } else {
8 high = mid;
9 }
10 }
11 return nums[low];
12}
13
14const nums = [3, 4, 5, 1, 2];
15console.log("Minimum is:", findMin(nums));
The JavaScript function findMin
employs binary search to isolate the minimal element in an array with rotating sorted nature. By adjusting the low
and high
indices, it simplifies the array into segments as dictated by comparisons, ultimately returning the rotated minimum.
This approach involves linearly iterating through the array to find the minimum value. While it doesn't meet the time complexity requirement of O(log n), it serves as a straightforward method to understand the array's properties and validate the binary search approach.
Time Complexity: O(n), as it requires traversal of the entire array in the worst-case scenario.
Space Complexity: O(1), with no additional space usage outside the input list.
1public class Main {
2 public static int findMin(int[] nums) {
3 int min = nums[0];
4 for (int num : nums) {
5 if (num < min) {
6 min = num;
7 }
8 }
9 return min;
10 }
11
12 public static void main(String[] args) {
13 int[] nums = {3, 4, 5, 1, 2};
14 System.out.println("Minimum is: " + findMin(nums));
15 }
16}
The Java method findMin
iteratively checks each number in the input array. It updates a minimum variable whenever a smaller element is found, thus systematically identifying the smallest value.