Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added firstlastposition.cpp
Empty file.
28 changes: 28 additions & 0 deletions min-rsortedarray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
public:
int findMin(vector<int>& 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;
}
};
31 changes: 31 additions & 0 deletions peakelement.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution {
public:
int findPeakElement(vector<int>& 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;
}
};