From e048a007719b6a0a22a05fa81b1bb824be0db6df Mon Sep 17 00:00:00 2001 From: Anomasingh <118592802+Anomasingh@users.noreply.github.com> Date: Sat, 27 Jan 2024 18:48:05 +0000 Subject: [PATCH] Solved Day-26 q3 in c++ Issue #560 --- .../Anomasingh--C.md | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Day-26/q3: Find first and last position of element in sorted array/Anomasingh--C.md 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