Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added solution to Q33 of Leetcode under issue #23 #29

Merged
merged 1 commit into from
Oct 3, 2022
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
As the array is sorted but rotated, so we figure out
which half of array is sorted, once we know which half of the array is
sorted, we perform a binary search to search for the target.

Complexity Analysis
TC(Time Complexity): O(log(N)) //Binary Search
SC(Space Complexity): O(1) //Constant Extra Space Used
*/
class Solution {
public:
int search(vector<int>& nums, int target) {
int n=nums.size();
int low=0;
int high=n-1;
while(low<=high){
int mid=(low+high)/2;
if(nums[mid]==target)
return mid;
//Checking if Left half is sorted
if(nums[low]<=nums[mid])
{
if(nums[low]<=target&&nums[mid]>target)
high=mid-1;
else
low=mid+1;
}
//Checking if Right half is sorted
else
{
if(nums[high]>=target&&nums[mid]<target)
low=mid+1;
else
high=mid-1;
}
}
return -1; //if target not found
}
};