[AlgoExpert] Search For Range

Search For Range

  • Time : O(logn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <vector>
using namespace std;

int minIndex(vector<int>& A, int& t) {
int l = 0, r = A.size() - 1, res = INT_MAX;
while(l <= r) {
int m = (l + r) / 2;
if(A[m] == t) res = min(res, m);
if(A[m] >= t) r = m - 1;
else l = m + 1;
}
if(res == INT_MAX or A[res] != t) return -1;
return res;
}

int maxIndex(vector<int>& A, int& t) {
int l = 0, r = A.size() - 1, res = -1;
while(l <= r) {
int m = (l + r) / 2;
if(A[m] == t) res = max(res, m);
if(A[m] <= t) l = m + 1;
else r = m - 1;
}
if(res == -1 or A[res] != t) return -1;
return res;
}

vector<int> searchForRange(vector<int> array, int target) {
// Write your code here.
return {minIndex(array, target), maxIndex(array, target)};
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/search-for-range/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.