diff --git a/Day-18/q2: Search in Rotated Sorted Array/Anomasingh--C.md b/Day-18/q2: Search in Rotated Sorted Array/Anomasingh--C.md new file mode 100644 index 00000000..97a9a23a --- /dev/null +++ b/Day-18/q2: Search in Rotated Sorted Array/Anomasingh--C.md @@ -0,0 +1,45 @@ +Solution in C++ + +Solved using Binary Search-- + +Code: +class Solution { +public: + int search(std::vector& nums, int target) + { + int l = 0; + int h = nums.size() - 1; + + while (l <= h) + { + int m = l + (h - l) / 2; //Middle element in a array + + if (nums[m] == target) //When middle element is the target element + { + return m; + } + + if (nums[l] <= nums[m]) //When last element is smaller than mid element + { + if (nums[l] <= target && target < nums[m]) + { + h = m - 1; + } else + { + l = m + 1; + } + } + else + { + if (nums[m] < target && target <= nums[h]) // When middle element is less than target element + { + l = m + 1; + } else { + h = m - 1; + } + } + } + + return -1; + } +}; \ No newline at end of file diff --git a/Day-26/q3: Find first and last position of element in sorted array/Anomasingh--C.md b/Day-26/q3: Find first and last position of element in sorted array/Anomasingh--C.md new file mode 100644 index 00000000..b9c4d64a --- /dev/null +++ b/Day-26/q3: Find first and last position of element in sorted array/Anomasingh--C.md @@ -0,0 +1,61 @@ +``` +Solution: +In c++ + +#include +using namespace std; +int firstOcc(vector& arr, int n, int key) { // finding the first occurrence of that element + + int s = 0, e = n-1; + int mid = s + (e-s)/2; + int ans = -1; + while(s<=e) { + + if(arr[mid] == key){ + ans = mid; + e = mid - 1; + } + else if(key > arr[mid]) { //Shifting to right + s = mid + 1; + } + else if(key < arr[mid]) { //Shifting to left + e = mid - 1; + } + + mid = s + (e-s)/2; + } + return ans; +} + +int lastOcc(vector& arr, int n, int key) { //finding the last occurrence of that element + + int s = 0, e = n-1; + int mid = s + (e-s)/2; + int ans = -1; + while(s<=e) { + + if(arr[mid] == key){ + ans = mid; + s = mid + 1; + } + else if(key > arr[mid]) { // Shifting to right + s = mid + 1; + } + else if(key < arr[mid]) { //Shifting to left + e = mid - 1; + } + + mid = s + (e-s)/2; + } + return ans; +} + +pair firstAndLastPosition(vector& arr, int n, int k) +{ + pair p; + p.first = firstOcc(arr, n, k); + p.second = lastOcc(arr, n, k); + + return p; +} +``` \ No newline at end of file