From 370dcf48773cecbc0d1e49cc139da2e81ceeedec Mon Sep 17 00:00:00 2001 From: rbhargav0104 Date: Sat, 27 Dec 2025 16:08:59 +0530 Subject: [PATCH] Completed Binary Search 2 --- firstlastposition.cpp | 0 min-rsortedarray.cpp | 28 ++++++++++++++++++++++++++++ peakelement.cpp | 31 +++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 firstlastposition.cpp create mode 100644 min-rsortedarray.cpp create mode 100644 peakelement.cpp diff --git a/firstlastposition.cpp b/firstlastposition.cpp new file mode 100644 index 00000000..e69de29b diff --git a/min-rsortedarray.cpp b/min-rsortedarray.cpp new file mode 100644 index 00000000..52dfbdd8 --- /dev/null +++ b/min-rsortedarray.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int findMin(vector& nums) { + int n = nums.size(); + int low = 0 ; + int high = nums.size() - 1; + + while(low <=high){ + if(nums[low]<= nums[high]) return nums[low];//only true when the array is sorted and not rotated + + 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]; + //case 1: mid at 0th index + //case 2: mid at last index + //case 3: mid is somewhere in between and we are checking if neighbours are greater or not + + else if(nums[low] <= nums[mid]){ + low = mid + 1;//minimum lies in right of mid + } + else{ + high = mid - 1;//minimum lies in the left of mid + } + } + + return -1; + } +}; \ No newline at end of file diff --git a/peakelement.cpp b/peakelement.cpp new file mode 100644 index 00000000..1bfa3ce7 --- /dev/null +++ b/peakelement.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int findPeakElement(vector& nums) { + int n = nums.size(); + int low = 0; + int high = n - 1; + + while(low <= high){ + int mid = low + (high - low )/2; + + if((mid == 0 || nums[mid] > nums[mid -1]) && (mid == n - 1 || nums[mid] > nums[mid + 1])){ + //case 1 : mid at 0th index and greater than the 1st index element + //case 2 : mid at the last index and greater than the penultimate index element + //case 3 : checking if the mid is greater than its neighbours or not + return mid; + } + + else if(mid < n-1 && nums[mid] < nums[mid+1]){ + // making sure mid doesnt go out of bounds + // here mid is less than mid + 1,hence we move to the right of mid + low = mid + 1; + } + + else{ //if(nums[mid] > nums[mid+1]) + high = mid - 1; + } + } + + return -1; + } +}; \ No newline at end of file