diff --git a/Day-18/q2: Search in Rotated Sorted Array/avanimathur--C.cpp b/Day-18/q2: Search in Rotated Sorted Array/avanimathur--C.cpp new file mode 100644 index 00000000..44eec40c --- /dev/null +++ b/Day-18/q2: Search in Rotated Sorted Array/avanimathur--C.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +class Solution { +public: + + int search(const vector& nums, int target) { + + if (nums.empty()) { + return -1; + } + + int left = 0, right = nums.size() - 1; + while (left < right) { + int mid = (left + right) / 2; + + if (nums[mid] > nums[right]) { + left = mid + 1; + } else { + right = mid; + } + } + + int pivot = left; + + left = 0; + right = nums.size() - 1; + + while (left <= right) { + int mid = (left + right) / 2; + int midVal = nums[(mid + pivot) % nums.size()]; + + if (midVal == target) { + return (mid + pivot) % nums.size(); + } else if (midVal < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return -1; + } +};