codekofi
← All problems

Problem 25

Hard

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

1double solution(vector<int> a, vector<int> b) {
2
3 if (a.size() > b.size()) {
4 swap(a, b);
5 }
6
7 int m = a.size();
8 int n = b.size();
9 int half = (m + n + 1) / 2;
10
11 int lo = 0;
12 int hi = m;
13
14 while (lo <= hi) {
15
16 int i = lo + (hi - lo) / 2;
17 int j = half - i;
18
19 int aLeft = (i == 0) ? INT_MIN : a[i - 1];
20 int aRight = (i == m) ? INT_MAX : a[i];
21 int bLeft = (j == 0) ? INT_MIN : b[j - 1];
22 int bRight = (j == n) ? INT_MAX : b[j];
23
24 if (aLeft <= bRight && bLeft <= aRight) {
25
26 int leftTop = max(aLeft, bLeft);
27
28 if ((m + n) % 2 == 1) {
29 return leftTop;
30 }
31
32 int rightLow = min(aRight, bRight);
33 return (leftTop + rightLow) / 2.0;
34 }
35
36 if (aLeft > bRight) {
37 hi = i - 1;
38 } else {
39 lo = i + 1;
40 }
41 }
42
43 return 0.0;
44}

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.