Binary search is one of those algorithms that's easy to understand the idea of, but it's often hard to work out the implementation details. For example, should it be $\text{lo}=0$ or $\text{lo}=1$? Should I set $\text{lo}$ to $\text{mid}$ or $\text{mid}+1$? Is the answer going to be $\text{lo}$ or $\text{hi}$? The questions are endless. As a result, I'd like to share with you a perspective on binary search that makes it easier to implement without bugs (in my opinion), and also more general. It involves abstracting out the actual binary search step by thinking of it as a method of finding a $[0,1]$ subarray in an array of $0$'s and $1$'s. After doing this, we find that binary search can be applied to search predicates that aren't monotone, allowing it to be applied to more problems that wouldn't usually be considered binary search at a glance. I hope you find it helpful!↵
↵
Also, huge thanks to my friends: [user:Wobert,2026-01-16] and [user:andrewtam,2026-01-16] for proofreading! :)↵
↵
Motivating Problem↵
==================↵
Suppose you're given an array $\text{A}$ of $0$s and $1$s indexed from $1$ to $n$. Additionally, you know:↵
↵
- $A[1] = 0$↵
- $A[n] = 1$↵
↵
Your goal is to find _consecutive_ indices $\ell$ and $r$ so that:↵
↵
- $1\leq\ell<r\leq n$↵
- $A[\ell]=0$↵
- $A[r]=1$↵
↵
Of course you could loop $\ell$ from $1$ to $n-1$ and compare it with $\ell+1$, but it is possible to do much better than linear.↵
↵
<spoiler summary="Logarithmic solution">↵
The key piece of information turns out to be that $A[1] = 0$ and $A[n] = 1$. If we didn't have this, linear is the best we can do. One way to interpret this info is that at some point between $1$ and $n$, we _switch_ from $0$ to $1$. As a result, we can check the index $m$ that's half-way between $1$ and $n$.↵
↵
If $A[m]=0$, then we can repeat the argument and see that we must switch from $0$ to $1$ at some point between $m$ and $n$. So, we can solve the problem in the right half. Similarly, if $A[m]=1$, then we must switch from $0$ to $1$ at some point between $1$ and $m$. We may then solve the problem in the left half.↵
</spoiler>↵
↵
<spoiler summary="Implementation">↵
The code turns out to be very simple. The exit condition `(r - l) > 1` makes us continue until `l` and `r` are consecutive.↵
↵
~~~~~↵
int l = 1;↵
int r = n;↵
↵
while ((r - l) > 1) {↵
int m = midpoint(l, r);↵
if(A[m]) r = m;↵
else l = m;↵
}↵
~~~~~↵
↵
Notice that before the loop starts and after every iteration, we know:↵
↵
- `A[l] = 0`↵
- `A[r] = 1`↵
- `l < r`↵
↵
This ensures that we've found a solution.↵
</spoiler>↵
↵
Generalizing Using Predicates↵
==================↵
I hope you agree that the implementation of the above solution is quite clean and essentially writes itself once you understand the idea. Wouldn't it be nice if **every** binary search problem could be solved just like this? It turns out that we can do just that! The above problem is the quintessential binary search problem. At its very core, binary search is not related to sorted arrays at all.↵
↵
To generalize this, we have to define a concept called a predicate. A real predicate in math is something abstract, but for us, a predicate is a function that assigns $0$ (false) or $1$ (true) to each integer in $[\ell,r]$. Essentially, it allows us to create an array consisting of $0$s and $1$s as in the motivating problem: $[ P(\ell),P(\ell+1),\dots,P(r) ]$↵
↵
Predicate Example↵
==================↵
To see an example of how all of this comes together, we'll solve the problem of finding the index of a value in a sorted array; this is the usual problem that motivates binary search. Formally, you're given a sorted integer array $A$ indexed from $1$ to $n$ and an integer $v$. Your goal is to find the first (i.e. smallest) index of $A$ where $v$ occurs (for simplicity, we assume $v$ exists in $A$).↵
↵
To set this problem up, we'll define the predicate: $P(i) := v \leq A[i]$. To see why this is what we want, notice that finding the first index $j$ where $A[j]=v$ is the same as finding consecutive $i$ and $j$ such that $A[i]<v\leq A[j]$. This works perfectly fine as long as the first occurrence of $v$ is not at the beginning of the array, this is because we wanted $A[i]<v$, but $j$ could be the first index. To get around this, we'll define our predicate on: $\\{0,1,\dots,n\\}$ and specifically set $P(0) = 0$. If it's not clear that this is what we want, consider the following example array and corresponding predicate values with $v=5$:↵
$$↵
\begin{equation}↵
\begin{split}↵
A&=[1,3,4,5,6,7,9]\\↵
P&=[0,0,0,1,1,1,1]↵
\end{split}↵
\end{equation}↵
$$↵
↵
The code looks like this:↵
↵
~~~~~↵
int search(vector<int> &A, int v, int n){↵
auto P = [&](int i) -> int {↵
if(i == 0) return 0;↵
return v <= A[i];↵
};↵
↵
int l = 0;↵
int r = n;↵
while((r - l) > 1){↵
int m = midpoint(l, r);↵
if(P(m)) r = m;↵
else l = m;↵
}↵
↵
return r;↵
}↵
~~~~~↵
Note↵
------------------↵
It's actually not necessary to define our predicate at $0$. This is because `midpoint(l, r)` will always return an integer that's strictly between $\ell$ and $r$ as long as their distance is greater than $1$. Generally speaking, we don't have to define our predicate at either endpoint $\ell$ or $r$, and we may assume $P(\ell)=0$ and $P(r)=1$.↵
↵
Remark↵
------------------↵
This problem gives an example of a monotone predicate. This is a predicate where if you increase the input, the output increases (non-strictly) as well. This is the kind of predicate that appears in 99% of binary search problems. With such a predicate, there can never be multiple consecutive pairs $\ell$ and $r$ such that $P(\ell)=0$ and $P(r)=1$. Hence, in these cases, our algorithm will always return the only possible answer. The same _cannot_ be said for the next example.↵
↵
[CSES: Colored Chairs](https://cses.fi/problemset/task/3273)↵
==================↵
↵
<spoiler summary = "Solution">↵
We'll apply our binary search technique of non-monotone predicates to this CSES problem. Let's imagine arranging the chairs in a line, you can imagine drawing a line between chairs $1$ and $n$ to signify that they're connected. First, notice that there will always be two adjacent chairs with the same colour (this has to do with the $n$ being odd condition). Next, we'll reduce the problem down to being on an array instead of a circle. To do this, first query chairs $1$ and $n$: if they have the same colour, we're done. Therefore, we assume chairs $1$ and $n$ have different colours and hence we may ignore that they're connected cyclically.↵
↵
After making this reduction, it turns out that the problem is equivalent to having an array $A$ of odd-length containing integers $0$ and $1$ such that $A[1]\neq A[n]$, and we want to find consecutive indices $1\leq i<j\leq n$ such that $A[i] = A[j]$. Do you see how similar this is to our original motivating problem? The only difference is that we wanted $A[i]\neq A[j]$ (in particular $A[i]=0$ and $A[j]=1$), and we knew $A[1] = 0$ and $A[n] = 1$.↵
↵
A convenient way to fix the former is to consider the parity of the index (even or odd) in our predicate. We'll do this using the XOR operation: $\oplus$. We can try: $P(i) := A[i] \oplus (i\text{ mod }2)$. The benefit of XOR is that if $i,j$ are consecutive and $A[i]=A[j]$, then $P(i)\neq P(j)$ (and vice versa).↵
↵
However, we want $P(1) = 0$ and $P(n) = 1$ in order to apply our binary search. So, to fix that we can instead consider: $P(i) := A[i] \oplus (i\text{ mod }2)\oplus A[1] \oplus 1$. It's not hard to see that $P(1) = 0$ and $P(n) = 1$ because we note that $A[1] \neq A[n]$ by our earlier reduction (and recall $n$ is odd). Now, the implementation is simple.↵
</spoiler>↵
↵
<spoiler summary = "Implementation">↵
~~~~~↵
#include <bits/stdc++.h>↵
using namespace std;↵
↵
int get(int i){↵
cout << "? " << i << endl;↵
char c;↵
cin >> c;↵
return c == 'R';↵
}↵
↵
void answer(int i){↵
cout << "! " << i << endl;↵
}↵
↵
int main(){↵
int n;↵
cin >> n;↵
↵
// first, we determine if the first and last chairs are the same colour↵
int c1 = get(1);↵
int cn = get(n);↵
if(c1 == cn){↵
answer(n);↵
return 0;↵
}↵
↵
// otherwise, we binary search on our predicate↵
auto P = [&](int i) -> int {↵
return get(i) ^ 1 ^ c1 ^ (i % 2);↵
};↵
↵
// template binary search↵
int l = 1;↵
int r = n;↵
↵
while((r - l) > 1){↵
int m = midpoint(l, r);↵
if(P(m)) r = m;↵
else l = m;↵
}↵
↵
// now, P(l) = 0 and P(r) = 1 (and they're one apart)↵
// so we can report l↵
answer(l);↵
}↵
~~~~~↵
</spoiler>↵
↵
[Kattis: Always Know Where Your Towel Is](https://open.kattis.com/problems/alwaysknowwhereyourtowelis)↵
==================↵
We can also use the non-monotone predicate idea in this problem. I highly recommend solving (or at least knowing the idea of) [CSES: Meet in the Middle](https://cses.fi/problemset/task/1628) first.↵
↵
<spoiler summary="Solution">↵
The main idea of the meet in the middle problem above is that we're able to calculate the following function in $\mathcal O(n2^{n/2})$: $S(i)$ which equals the number of subsets (of the given set) whose sum is $i$. After implementing this, you may realize that after an $\mathcal O(n2^{n/2})$ preprocessing step, we're able to not only calculate $S(i)$ in $\mathcal O(2^{n/2})$ time, but we can also calculate the function $S(\leq i)$: which equals the number of subsets whose sum is at most $i$. This function will be used in our predicate. Before continuing, we note that only non-empty subsets are of interest to us in this question, so that's always what we mean by "subset" from now on.↵
↵
Recall that by definition, we have: $S(\leq 2^n-2)=2^n-1$. In particular, $S(\leq 2^n-2)>2^n-2$. This was the reason we're guaranteed to have two subsets with the same sum. Generalizing, observe that if $S(\leq i)>i$, then there must exist two subsets that both sum to the same value which is at most $i$. This inspires us to make our predicate: $P(i) := S(\leq i) > i$. Indeed, if we have consecutive $i$ and $j$ such that $P(i)=0$ and $P(j)=1$, we can prove that there exist two subsets summing to $j$. Note:↵
$$↵
\begin{equation}↵
\begin{split}↵
S(j) &= S(\leq j) - S(\leq i)\\↵
&>j - S(\leq i)\\↵
&\geq j - i\\↵
&=1\text{ as wanted}↵
\end{split}↵
\end{equation}↵
$$↵
Therefore, we may use binary search on this problem. We set $\ell=0$ since $P(0)=0$, and we set $r=2^n-2$ as $P(2^n-2)=1$. Also, since $\log(r-\ell)<\log(2^n)=n$, the complexity of this step will be $\mathcal O(n2^{n/2})$ as evaluating the predicate takes $\mathcal O(2^{n/2})$ time.↵
</spoiler>↵
↵
<spoiler summary="Implementation">↵
~~~~~↵
#include <bits/stdc++.h>↵
using namespace std;↵
using ll = long long;↵
↵
// compute the sum of every subset of the input vector, and return it in sorted order↵
vector<ll> all_sums(vector<ll>a){↵
int n = a.size();↵
vector<ll>sums(1 << n);↵
for(int i=0; i<1<<n; i++){↵
for(int j=0; j<n; j++)↵
sums[i] += a[j] * (1 & (i >> j));↵
}↵
sort(sums.begin(), sums.end());↵
return sums;↵
}↵
↵
int main(){↵
int n;↵
cin >> n;↵
↵
// split the input into two arrays as in the meet in the middle technique↵
vector<ll> v1, v2;↵
for(int i=0; i<n; i++){↵
ll v;↵
cin >> v;↵
if(i&1) v1.push_back(v);↵
else v2.push_back(v);↵
}↵
↵
auto s1 = all_sums(v1), s2 = all_sums(v2);↵
↵
// compute our S(<= m) function with 2-pointers↵
auto S = [&](ll m) {↵
ll s = 0;↵
int j = s2.size() - 1;↵
for(int i=0; i<s1.size(); i++){↵
while(j >= 0 && s1[i] + s2[j] > m) j--;↵
s += j+1;↵
}↵
return s - 1; // subtract the empty set↵
};↵
↵
auto P = [&](ll i) {↵
return S(i) > i;↵
};↵
↵
// template binary search↵
ll l = 0;↵
ll r = (1ll << n) - 2;↵
↵
while((r - l) > 1){↵
ll m = midpoint(l, r);↵
if(P(m)) r = m;↵
else l = m;↵
}↵
↵
cout << r << '\n';↵
}↵
~~~~~↵
</spoiler>↵
↵
Bonus Binary Search Trick↵
==================↵
Lastly, I want to share a trick that has been useful to me in one of the discussion problems below. It turns out that we can generalize the "template binary search" algorithm introduced at the start, we don't need $\ell<r$. As long as $\ell\neq r$, $P(\ell)=0$ and $P(r)=1$, then we may do binary search as follows:↵
↵
~~~~~↵
while (abs(r - l) > 1) {↵
int m = midpoint(l, r);↵
if(P(m)) r = m;↵
else l = m;↵
}↵
~~~~~↵
↵
This could be useful in avoiding having to consider cases when $\ell<r$ and $\ell>r$, for example. To see why it works, we focus on the new case where $\ell>r$. Then, the same loop invariant as in the original proof applies, with the one modification that $\ell>r$. In the end, $\ell,r$ will still be consecutive as their distance will be $1$.↵
↵
Conclusion↵
==================↵
Thank you for reading! In my experience, this binary search technique is pretty unknown/under appreciated. However, it can be powerful for solving many problems in a clean/less error-prone way. Even if your predicate happens to be monotonic, I still believe thinking about binary search as the algorithm that finds a consecutive $[0,1]$ can make the implementation feel a lot more grounded. IMHO, this is how binary search _should_ be taught :^)↵
↵
Discussion Problems↵
==================↵
I've included a few problems that can be solved using the binary search techniques discussed in this blog. Feel free to solve them and discuss your solutions in the comments :)↵
Also, if you know of any additional problems that do a good job of showcasing these techniques, please comment and I'll add them.↵
↵
- [CSES: Same Sum Subsets](https://cses.fi/problemset/task/3425/): Harder version of "Always Know Where Your Towel Is"↵
- [MofK's Mysterious Money Making Machine](https://oj.vnoi.info/problem/icpc23_national_m)
↵
Also, huge thanks to my friends: [user:Wobert,2026-01-16] and [user:andrewtam,2026-01-16] for proofreading! :)↵
↵
Motivating Problem↵
==================↵
Suppose you're given an array $\text{A}$ of $0$s and $1$s indexed from $1$ to $n$. Additionally, you know:↵
↵
- $A[1] = 0$↵
- $A[n] = 1$↵
↵
Your goal is to find _consecutive_ indices $\ell$ and $r$ so that:↵
↵
- $1\leq\ell<r\leq n$↵
- $A[\ell]=0$↵
- $A[r]=1$↵
↵
Of course you could loop $\ell$ from $1$ to $n-1$ and compare it with $\ell+1$, but it is possible to do much better than linear.↵
↵
<spoiler summary="Logarithmic solution">↵
The key piece of information turns out to be that $A[1] = 0$ and $A[n] = 1$. If we didn't have this, linear is the best we can do. One way to interpret this info is that at some point between $1$ and $n$, we _switch_ from $0$ to $1$. As a result, we can check the index $m$ that's half-way between $1$ and $n$.↵
↵
If $A[m]=0$, then we can repeat the argument and see that we must switch from $0$ to $1$ at some point between $m$ and $n$. So, we can solve the problem in the right half. Similarly, if $A[m]=1$, then we must switch from $0$ to $1$ at some point between $1$ and $m$. We may then solve the problem in the left half.↵
</spoiler>↵
↵
<spoiler summary="Implementation">↵
The code turns out to be very simple. The exit condition `(r - l) > 1` makes us continue until `l` and `r` are consecutive.↵
↵
~~~~~↵
int l = 1;↵
int r = n;↵
↵
while ((r - l) > 1) {↵
int m = midpoint(l, r);↵
if(A[m]) r = m;↵
else l = m;↵
}↵
~~~~~↵
↵
Notice that before the loop starts and after every iteration, we know:↵
↵
- `A[l] = 0`↵
- `A[r] = 1`↵
- `l < r`↵
↵
This ensures that we've found a solution.↵
</spoiler>↵
↵
Generalizing Using Predicates↵
==================↵
I hope you agree that the implementation of the above solution is quite clean and essentially writes itself once you understand the idea. Wouldn't it be nice if **every** binary search problem could be solved just like this? It turns out that we can do just that! The above problem is the quintessential binary search problem. At its very core, binary search is not related to sorted arrays at all.↵
↵
To generalize this, we have to define a concept called a predicate. A real predicate in math is something abstract, but for us, a predicate is a function that assigns $0$ (false) or $1$ (true) to each integer in $[\ell,r]$. Essentially, it allows us to create an array consisting of $0$s and $1$s as in the motivating problem: $[ P(\ell),P(\ell+1),\dots,P(r) ]$↵
↵
Predicate Example↵
==================↵
To see an example of how all of this comes together, we'll solve the problem of finding the index of a value in a sorted array; this is the usual problem that motivates binary search. Formally, you're given a sorted integer array $A$ indexed from $1$ to $n$ and an integer $v$. Your goal is to find the first (i.e. smallest) index of $A$ where $v$ occurs (for simplicity, we assume $v$ exists in $A$).↵
↵
To set this problem up, we'll define the predicate: $P(i) := v \leq A[i]$. To see why this is what we want, notice that finding the first index $j$ where $A[j]=v$ is the same as finding consecutive $i$ and $j$ such that $A[i]<v\leq A[j]$. This works perfectly fine as long as the first occurrence of $v$ is not at the beginning of the array, this is because we wanted $A[i]<v$, but $j$ could be the first index. To get around this, we'll define our predicate on: $\\{0,1,\dots,n\\}$ and specifically set $P(0) = 0$. If it's not clear that this is what we want, consider the following example array and corresponding predicate values with $v=5$:↵
$$↵
\begin{equation}↵
\begin{split}↵
A&=[1,3,4,5,6,7,9]\\↵
P&=[0,0,0,1,1,1,1]↵
\end{split}↵
\end{equation}↵
$$↵
↵
The code looks like this:↵
↵
~~~~~↵
int search(vector<int> &A, int v, int n){↵
auto P = [&](int i) -> int {↵
if(i == 0) return 0;↵
return v <= A[i];↵
};↵
↵
int l = 0;↵
int r = n;↵
while((r - l) > 1){↵
int m = midpoint(l, r);↵
if(P(m)) r = m;↵
else l = m;↵
}↵
↵
return r;↵
}↵
~~~~~↵
Note↵
------------------↵
It's actually not necessary to define our predicate at $0$. This is because `midpoint(l, r)` will always return an integer that's strictly between $\ell$ and $r$ as long as their distance is greater than $1$. Generally speaking, we don't have to define our predicate at either endpoint $\ell$ or $r$, and we may assume $P(\ell)=0$ and $P(r)=1$.↵
↵
Remark↵
------------------↵
This problem gives an example of a monotone predicate. This is a predicate where if you increase the input, the output increases (non-strictly) as well. This is the kind of predicate that appears in 99% of binary search problems. With such a predicate, there can never be multiple consecutive pairs $\ell$ and $r$ such that $P(\ell)=0$ and $P(r)=1$. Hence, in these cases, our algorithm will always return the only possible answer. The same _cannot_ be said for the next example.↵
↵
[CSES: Colored Chairs](https://cses.fi/problemset/task/3273)↵
==================↵
↵
<spoiler summary = "Solution">↵
We'll apply our binary search technique of non-monotone predicates to this CSES problem. Let's imagine arranging the chairs in a line, you can imagine drawing a line between chairs $1$ and $n$ to signify that they're connected. First, notice that there will always be two adjacent chairs with the same colour (this has to do with the $n$ being odd condition). Next, we'll reduce the problem down to being on an array instead of a circle. To do this, first query chairs $1$ and $n$: if they have the same colour, we're done. Therefore, we assume chairs $1$ and $n$ have different colours and hence we may ignore that they're connected cyclically.↵
↵
After making this reduction, it turns out that the problem is equivalent to having an array $A$ of odd-length containing integers $0$ and $1$ such that $A[1]\neq A[n]$, and we want to find consecutive indices $1\leq i<j\leq n$ such that $A[i] = A[j]$. Do you see how similar this is to our original motivating problem? The only difference is that we wanted $A[i]\neq A[j]$ (in particular $A[i]=0$ and $A[j]=1$), and we knew $A[1] = 0$ and $A[n] = 1$.↵
↵
A convenient way to fix the former is to consider the parity of the index (even or odd) in our predicate. We'll do this using the XOR operation: $\oplus$. We can try: $P(i) := A[i] \oplus (i\text{ mod }2)$. The benefit of XOR is that if $i,j$ are consecutive and $A[i]=A[j]$, then $P(i)\neq P(j)$ (and vice versa).↵
↵
However, we want $P(1) = 0$ and $P(n) = 1$ in order to apply our binary search. So, to fix that we can instead consider: $P(i) := A[i] \oplus (i\text{ mod }2)\oplus A[1] \oplus 1$. It's not hard to see that $P(1) = 0$ and $P(n) = 1$ because we note that $A[1] \neq A[n]$ by our earlier reduction (and recall $n$ is odd). Now, the implementation is simple.↵
</spoiler>↵
↵
<spoiler summary = "Implementation">↵
~~~~~↵
#include <bits/stdc++.h>↵
using namespace std;↵
↵
int get(int i){↵
cout << "? " << i << endl;↵
char c;↵
cin >> c;↵
return c == 'R';↵
}↵
↵
void answer(int i){↵
cout << "! " << i << endl;↵
}↵
↵
int main(){↵
int n;↵
cin >> n;↵
↵
// first, we determine if the first and last chairs are the same colour↵
int c1 = get(1);↵
int cn = get(n);↵
if(c1 == cn){↵
answer(n);↵
return 0;↵
}↵
↵
// otherwise, we binary search on our predicate↵
auto P = [&](int i) -> int {↵
return get(i) ^ 1 ^ c1 ^ (i % 2);↵
};↵
↵
// template binary search↵
int l = 1;↵
int r = n;↵
↵
while((r - l) > 1){↵
int m = midpoint(l, r);↵
if(P(m)) r = m;↵
else l = m;↵
}↵
↵
// now, P(l) = 0 and P(r) = 1 (and they're one apart)↵
// so we can report l↵
answer(l);↵
}↵
~~~~~↵
</spoiler>↵
↵
[Kattis: Always Know Where Your Towel Is](https://open.kattis.com/problems/alwaysknowwhereyourtowelis)↵
==================↵
We can also use the non-monotone predicate idea in this problem. I highly recommend solving (or at least knowing the idea of) [CSES: Meet in the Middle](https://cses.fi/problemset/task/1628) first.↵
↵
<spoiler summary="Solution">↵
The main idea of the meet in the middle problem above is that we're able to calculate the following function in $\mathcal O(n2^{n/2})$: $S(i)$ which equals the number of subsets (of the given set) whose sum is $i$. After implementing this, you may realize that after an $\mathcal O(n2^{n/2})$ preprocessing step, we're able to not only calculate $S(i)$ in $\mathcal O(2^{n/2})$ time, but we can also calculate the function $S(\leq i)$: which equals the number of subsets whose sum is at most $i$. This function will be used in our predicate. Before continuing, we note that only non-empty subsets are of interest to us in this question, so that's always what we mean by "subset" from now on.↵
↵
Recall that by definition, we have: $S(\leq 2^n-2)=2^n-1$. In particular, $S(\leq 2^n-2)>2^n-2$. This was the reason we're guaranteed to have two subsets with the same sum. Generalizing, observe that if $S(\leq i)>i$, then there must exist two subsets that both sum to the same value which is at most $i$. This inspires us to make our predicate: $P(i) := S(\leq i) > i$. Indeed, if we have consecutive $i$ and $j$ such that $P(i)=0$ and $P(j)=1$, we can prove that there exist two subsets summing to $j$. Note:↵
$$↵
\begin{equation}↵
\begin{split}↵
S(j) &= S(\leq j) - S(\leq i)\\↵
&>j - S(\leq i)\\↵
&\geq j - i\\↵
&=1\text{ as wanted}↵
\end{split}↵
\end{equation}↵
$$↵
Therefore, we may use binary search on this problem. We set $\ell=0$ since $P(0)=0$, and we set $r=2^n-2$ as $P(2^n-2)=1$. Also, since $\log(r-\ell)<\log(2^n)=n$, the complexity of this step will be $\mathcal O(n2^{n/2})$ as evaluating the predicate takes $\mathcal O(2^{n/2})$ time.↵
</spoiler>↵
↵
<spoiler summary="Implementation">↵
~~~~~↵
#include <bits/stdc++.h>↵
using namespace std;↵
using ll = long long;↵
↵
// compute the sum of every subset of the input vector, and return it in sorted order↵
vector<ll> all_sums(vector<ll>a){↵
int n = a.size();↵
vector<ll>sums(1 << n);↵
for(int i=0; i<1<<n; i++){↵
for(int j=0; j<n; j++)↵
sums[i] += a[j] * (1 & (i >> j));↵
}↵
sort(sums.begin(), sums.end());↵
return sums;↵
}↵
↵
int main(){↵
int n;↵
cin >> n;↵
↵
// split the input into two arrays as in the meet in the middle technique↵
vector<ll> v1, v2;↵
for(int i=0; i<n; i++){↵
ll v;↵
cin >> v;↵
if(i&1) v1.push_back(v);↵
else v2.push_back(v);↵
}↵
↵
auto s1 = all_sums(v1), s2 = all_sums(v2);↵
↵
// compute our S(<= m) function with 2-pointers↵
auto S = [&](ll m) {↵
ll s = 0;↵
int j = s2.size() - 1;↵
for(int i=0; i<s1.size(); i++){↵
while(j >= 0 && s1[i] + s2[j] > m) j--;↵
s += j+1;↵
}↵
return s - 1; // subtract the empty set↵
};↵
↵
auto P = [&](ll i) {↵
return S(i) > i;↵
};↵
↵
// template binary search↵
ll l = 0;↵
ll r = (1ll << n) - 2;↵
↵
while((r - l) > 1){↵
ll m = midpoint(l, r);↵
if(P(m)) r = m;↵
else l = m;↵
}↵
↵
cout << r << '\n';↵
}↵
~~~~~↵
</spoiler>↵
↵
Bonus Binary Search Trick↵
==================↵
Lastly, I want to share a trick that has been useful to me in one of the discussion problems below. It turns out that we can generalize the "template binary search" algorithm introduced at the start, we don't need $\ell<r$. As long as $\ell\neq r$, $P(\ell)=0$ and $P(r)=1$, then we may do binary search as follows:↵
↵
~~~~~↵
while (abs(r - l) > 1) {↵
int m = midpoint(l, r);↵
if(P(m)) r = m;↵
else l = m;↵
}↵
~~~~~↵
↵
This could be useful in avoiding having to consider cases when $\ell<r$ and $\ell>r$, for example. To see why it works, we focus on the new case where $\ell>r$. Then, the same loop invariant as in the original proof applies, with the one modification that $\ell>r$. In the end, $\ell,r$ will still be consecutive as their distance will be $1$.↵
↵
Conclusion↵
==================↵
Thank you for reading! In my experience, this binary search technique is pretty unknown/under appreciated. However, it can be powerful for solving many problems in a clean/less error-prone way. Even if your predicate happens to be monotonic, I still believe thinking about binary search as the algorithm that finds a consecutive $[0,1]$ can make the implementation feel a lot more grounded. IMHO, this is how binary search _should_ be taught :^)↵
↵
Discussion Problems↵
==================↵
I've included a few problems that can be solved using the binary search techniques discussed in this blog. Feel free to solve them and discuss your solutions in the comments :)↵
Also, if you know of any additional problems that do a good job of showcasing these techniques, please comment and I'll add them.↵
↵
- [CSES: Same Sum Subsets](https://cses.fi/problemset/task/3425/): Harder version of "Always Know Where Your Towel Is"↵
- [MofK's Mysterious Money Making Machine](https://oj.vnoi.info/problem/icpc23_national_m)



