Find Range I: Solving Coding Questions #1

Find Range I

Give it a shot, then come back if you get stuck or find a solution.

Solution #1

Code (C++)

pair<int, int> find_range(vector<int> arr, int target) {
for(int i = 1; i < arr.size(); i++) {
if(arr[i-1] <= target && arr[i] >= target)
return {arr[i-1], arr[i]};
}
return {-1, -1};
}

Solution #2

Code (C++)

pair<int, int> find_range(vector<int> arr, int target) {  int low = 0, high = arr.size() - 1, mid;    while(low <= high) {
mid = (high + low) / 2;
if(arr[mid] <= target && arr[mid + 1] >= target) {
return {arr[mid], arr[mid+1]};
} else if(arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return {-1, -1};
}

Code (C++)

if(arr[mid] != arr[mid + 1])  return {arr[mid], arr[mid + 1]};if(arr[mid - 1] != arr[mid] && arr[mid] == arr[mid + 1])  return {arr[mid - 1], arr[mid]};high = mid - 1;

Code (C++)

pair<int, int> find_range(vector<int> arr, int target) {
int low = 0, high = arr.size() - 1, mid;
while(low <= high) {
mid = low + ((high - low) / 2);
if(arr[mid] <= target && arr[mid + 1] >= target) {
if(arr[mid] != arr[mid + 1])
return {arr[mid], arr[mid + 1]};
if(arr[mid - 1] != arr[mid] && arr[mid] == arr[mid + 1])
return {arr[mid - 1], arr[mid]};
high = mid - 1;
} else if(arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return {-1, -1};
}

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store