Back to course home
0% completed
Vote For New Content
Recurssive solution for c++
lejafilip
Sep 15, 2024
vector<int> findRange(const vector<int> &arr, int key) { vector<int> result(2, -1); auto n = arr.size() - 1; if(arr[n] < key) return result; else if(arr[0] > key) return result; result[0] = findLeftIdx(arr, key, 0, n); result[1] = findRightIdx(arr, key, 0, n); return result; } int findLeftIdx(const vector<int> &arr, int key, int start, int end) { auto pivot = (start + end) / 2; if(start >= end) { if(arr[pivot] == key) return pivot; else if(pivot < arr.size() - 1 && arr[pivot + 1] == key) return pivot + 1; else return -1; } if(arr[pivot] >= key) return findLeftIdx(arr, key, start, pivot - 1); else return findLeftIdx(arr, key, pivot + 1, end); } int findRightIdx(const vector<int> &arr, int key, int start, int end) { auto pivot = (start + end) / 2; if(start >= end) { if(arr[pivot] == key) return pivot; else if(pivot > 0 && arr[pivot - 1] == key) return pivot -1; else return -1; } if(arr[pivot] <= key) return findRightIdx(arr, key, pivot + 1, end); else return findRightIdx(arr, key, start, pivot - 1); }
I am wondering if it would pass on FAANG interview?
0
0
Comments
Comments
On this page