From ba6284d78d0b623818490af267379de689d4853a Mon Sep 17 00:00:00 2001 From: Hriday-A Date: Sat, 11 Apr 2026 02:44:10 -0500 Subject: [PATCH] Completed Binary Search-2 Assignment --- 154_rotated_sorted_array_min.java | 28 +++++++++++++++++++++ 162_find_peak_element.java | 16 ++++++++++++ 34_find_first_and_last_element.java | 39 +++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 154_rotated_sorted_array_min.java create mode 100644 162_find_peak_element.java create mode 100644 34_find_first_and_last_element.java diff --git a/154_rotated_sorted_array_min.java b/154_rotated_sorted_array_min.java new file mode 100644 index 00000000..ed488206 --- /dev/null +++ b/154_rotated_sorted_array_min.java @@ -0,0 +1,28 @@ +class Solution { + public int findMin(int[] nums) { + int low =0; + int n = nums.length; + int high = n-1; + while(low<=high){ + if (nums[low]<=nums[high]) return nums[low]; + int mid = low + (high-low)/2; + if ((mid == 0 || nums[mid] < nums[mid - 1]) && + (mid == n - 1 || nums[mid] < nums[mid + 1])) { + return nums[mid]; + } + else if(nums[mid]>=nums[low]){ + low = mid + 1; + }else{ + high = mid -1 ; + } + } + + return -1; + } +} + +/*There are few things to consider to solve this question - +(1) The minimum is always on the other side of the sorted half - thats an observation +(2) Whenever you see that its a sorted array - think of Binary search (also it is O(logn)) +(3) One mistake that i made was while submitting it was to write the following statement - realised when dry run the attempt - if (nums[low]<=nums[high]) return nums[low]; +*/ diff --git a/162_find_peak_element.java b/162_find_peak_element.java new file mode 100644 index 00000000..4d0f882a --- /dev/null +++ b/162_find_peak_element.java @@ -0,0 +1,16 @@ +class Solution { + public int findPeakElement(int[] nums) { + // concept of slope was introduced here + // where every there is slope - we use binary search + // till now our thought process was binary search == sorted array but it changes a bit here + int low =0 ; + int high = nums.length - 1; + while (low<=high){ + int mid = low + (high-low)/2; + if ((mid==0 || nums[mid]>nums[mid-1])&&(mid==nums.length - 1 || nums[mid]>nums[mid+1])) return mid; + else if (nums[mid]target){ + high = mid - 1; + }else low = mid+1; + } + return -1; + } + private int binarySearchLast(int[] nums,int low,int high, int target){ + while(low<=high){ + int mid = low + (high - low)/2; + if(nums[mid] == target){ + if(mid == nums.length-1 || nums[mid+1] != target) return mid; + else low = mid +1; + } + else if (nums[mid]>target){ + high = mid - 1; + }else low = mid+1; + } + return -1; + } +} + +// We used two binary search indivually to find the values for the first and last +// also for values with just single value it should return the same postion twice - like if 5 appears at 0 -{0,0} \ No newline at end of file