From 6ac73f8451ec07c1ecd5013a026e48b399adf2c5 Mon Sep 17 00:00:00 2001 From: firoz Syed Date: Sat, 26 Oct 2024 21:44:41 -0700 Subject: [PATCH] Binary-Search-2 Completed --- FindMinInSortedArray.java | 52 ++++++++++++++++++++++++++++++++++++++ FindPeakElement.java | 22 ++++++++++++++++ FirstAndLastElement.java | 53 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 127 insertions(+) create mode 100644 FindMinInSortedArray.java create mode 100644 FindPeakElement.java create mode 100644 FirstAndLastElement.java diff --git a/FindMinInSortedArray.java b/FindMinInSortedArray.java new file mode 100644 index 00000000..de33c500 --- /dev/null +++ b/FindMinInSortedArray.java @@ -0,0 +1,52 @@ +// Time Complexity: O(logn) +// Space Complexity : O(1) +// Approach : Apply Binary Search to reduce the search range by moving the pointer towards unsorted portion as chances of min on the sorted portion is less. +class Solution { + public int findMin(int[] nums) { + int n = nums.length; + int low = 0; + int high = n-1; + while(low<=high){ + int mid = low + (high-low)/2; + // array rotated n times then it becomes sorted array + if(nums[low]<=nums[high]){ + return nums[low]; + } + // mid happen to be the pivot where the rotation happened + if((mid == 0 || (nums[mid-1] > nums[mid])) && (mid==high || (nums[mid+1] > nums[mid]))){ + return nums[mid]; + // right Array is sorted + }else if(nums[mid]nums[mid]) && (mid == high || nums[mid+1]>nums[mid])){ + return nums[mid] ;// on the pivot - rotation happend + } + // sorted portion is on right + if(nums[mid]0 && nums[mid]nums[mid]){ + return mid; + } else { + low = mid+1; + } + } else if(nums[mid]>target){ + high = mid-1; + } else{ + low = mid+1; + } + } + return -1; + } +} \ No newline at end of file