codekofi
← All problems

Problem 84

Medium

1 · Worked examples

0 / 4

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 4 outputs correctly.

The accepted solution

1int solution(const vector<int>& nums, int target) {
2
3 int n = nums.size();
4 int lo = 0;
5 int hi = n - 1;
6
7 while (lo <= hi) {
8
9 int mid = lo + (hi - lo) / 2;
10
11 if (nums[mid] == target) {
12 return mid;
13 }
14
15 if (nums[lo] <= nums[mid]) {
16
17 if (nums[lo] <= target && target < nums[mid]) {
18 hi = mid - 1;
19 } else {
20 lo = mid + 1;
21 }
22
23 } else {
24
25 if (nums[mid] < target && target <= nums[hi]) {
26 lo = mid + 1;
27 } else {
28 hi = mid - 1;
29 }
30 }
31 }
32
33 return -1;
34}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.