Skip to content

Commit

Permalink
Merge pull request #29 from vivek-dhiman/main
Browse files Browse the repository at this point in the history
Added solution to Q33 of Leetcode in cpp
  • Loading branch information
DugarRishab authored Oct 3, 2022
2 parents a9292ec + d9261da commit 1d01bb1
Showing 1 changed file with 39 additions and 0 deletions.
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
}
};

0 comments on commit 1d01bb1

Please sign in to comment.