Binary search is an even more op technique that has the power to reduce an
The most trivial use of binary search is to locate an element in a sorted array or report that it does not exist, in
Binary search however, is much, much, more than that. When you find yourself in a tough spot with no way out, no light at the end of the tunnel and in complete darkness, ask yourself this
Can I binary search the answer?
More often than not, the answer will be yes. A glimmer of hope, a shimmering light that marks the end of the tunnel. You start to slowly piece together the solution bit by bit, as you near the exit step by step. You've reached the end, the brightness now overwhelming, salvation at last. Mankind has never received a greater gift than binary search. Binary search is the way. Binary search is always the answer. Binary search is in itself, a religion. Join the cult, you won't regret it. Here are some inspiring quotes from our famous leaders
No more hunger, no more poverty. It's all thanks to binary search.
-- Mahatma Gandhi
It's genius. I wish I just did a binary search from the start. Damn!
-- Albert Einstein
Just binary search bro.
-- Julius Caesar
What are you waiting for? Join the cult NOW! JK.
Binary search is not limited to just searching for an element. You can even binary search the optimal answer to a problem.
Consider this problem.
Lets define a function true
if it is possible to make the answer at least false
.
✔️ | ✔️ | ✔️ | ✔️ | ❌ | ❌ | ❌ | ❌ |
Observe that if true
then even true
. Similarly, if false
then even false
. This yields a property which appears to be sorted (first all trues, followed by all falses). What we are looking for is the largest value of true
, which can be done with a simple binary search.
Here is my solution to the problem.
Reading material:
- The trivial algorithm - Medium [B]
- Binary search over the answer - Medium [B]
- A comprehensive tutorial
- Errichto [V]
- Topcoder [B]
- CPH Ch 3, pg 31 - 34
- CF EDU on Binary search
This page uses math latex formatting. Download the extension to render it.