by hiAndrewQuinn · 1y ago · 0 comments
Jon Bentley, the writer of Programming Pearls, gave the task of writing an ordinary binary search to a group of professional programmers at IBM, and found that 90% of their implementations contained bugs. The most common one seems to have been accidentally running into an infinite loop. To be fair, this was back in the day when integer overflows had to be explicitly guarded against - but even then, it's a surprising number.
[1]: https://hiandrewquinn.github.io/til-site/posts/binary-search...
That they work for binary search is a very strong signal to people not familiar with them that they work for nearly everything (they do).
I find this topic really interesting, thanks for sharing. I doubt I could code a binary search without any bugs from scratch :)
https://research.google/blog/extra-extra-read-all-about-it-n...
I think part of reason is that most people were taught a bad interface. Even the code on Wikipedia says “Set L to 0 and R to n-1”. That is, R is an inclusive bound. But we’ve learned that for most string algorithms, it is better when your upper bound is an exclusive bound, that is, n.
I’ve wanted to do an experiment testing that hypothesis. That is, ask a large number of people to write it with different function prototypes and initial calls and see how many buggy implementations I get with inclusive vs exclusive upperbound vs length.
L
== L[0:len(L)]
== L[0:l] + L[l:len(L)]
== L[0:l] + L[l:r] + L[r:len(L)]
I actually didn't like this syntax until I had to work this out. Now everyone else's approach seems silly to me.I vote for making "how would you think about proving this correct?" a question in all algo-focused interviews.
>about 2/3rds of highly credentialed applicants
Credentialed ≠ capable.
I'd be interested to know why you feel that this is a useful interview question.
Implementing a well-known and widely implemented algorithm under stressful interview conditions wouldn't seem to me to demonstrate much about a candidate. In that situation I'd much rather be given a printout of some code and asked to talk around the implementation - how the code maps to the abstract algorithm, implementation trade-offs, readability, etc.
Companies that don't fall into a culture like this are indeed deluded.
I would do the following:
1. Write a tax calculator that reads in data from a CSV, or a similar question to showcase programming ability.
2. Do a small paid project. If it was good enough, hire them. If it wasn't, then give feedback and do another one in a week, tell them to learn as much about the topic as possible.
3. Do a small paid project a week later. If their learning agility is high, then hire them still.
Prompt:
Please write a bug free binary search in python
Answer:
def binary_search(arr, target):
"""
Performs binary search on a sorted array.
Args:
arr: A sorted list of comparable elements
target: The element to search for
Returns:
The index of target if found, -1 otherwise
"""
left = 0
right = len(arr) - 1
while left <= right:
# Avoid potential overflow by using this formula
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# Example usage and test cases
if __name__ == "__main__":
# Test cases
test_array = [1, 3, 5, 7, 9, 11, 13, 15] print(binary_search(test_array, 7)) # Output: 3
print(binary_search(test_array, 1)) # Output: 0
print(binary_search(test_array, 15)) # Output: 7
print(binary_search(test_array, 4)) # Output: -1
print(binary_search([], 5)) # Output: -1
print(binary_search([5], 5)) # Output: 0
print(binary_search([5], 3)) # Output: -1 mid = left + (right - left) // 2
This implementation detail is to my knowledge unnecessary in Python because Python's built-in int type has arbitrary-precision integers. It's intended to avoid buffer overflows in languages like C.Imagine, say, that left is 1 and right is 2^63 - 1. In Python left + right will just give you 2^63, no big deal. In C, left + right will overflow and produce undefined behavior; in practice it usually gives you I think -2^63, which is obviously going to screw up the bsearch a bit. It isn't wrong, just slightly less idiomatic for the language.
Python's interpreter may or may not be able to recognize and refactor the slight inefficiency of the extra arithmetic operation out. I will only point out that most of the time when we write our own bsearch it's because we want to optimize something really fundamental to the codebase. Any time you have to whip up your own algorithm it's prima facie evidence that that part of the code might be good to profile.
The underlying problem is sloppy use of int for indices. The roundabout calculation will still overflow at twice the size.
In Python, the double slash (or type casting) is necessary as a single slash will yield a float by default. Double slash returns an int.
while (l < r)
{
//find the midpoint
auto mp = l + (l-r)/2;
if (nums[mp] == target) { prior = target;
#ifdef upper_bound
l = target + 1; // move the left bound up, maybe there's more up there we can look for!
#else
//lower bound, we found the highest known instance of target, but let's look in the exclusive left half a bit more
r = target - 1;
#endif
}
excuse the terrible formatting, it's been a long day grinding leetcode after getting laid off...
I have my rightmost code at part III of the miniseries, [1]. It loks quite similar, but I save the -1 for the very end return.
def rightmost_bsearch(L, T):
l, r = 0, len(L)
while l < r:
# Loop invariants. Always true! Comment out in production!
for somewhat_smol in L[0:l]:
assert somewhat_smol <= T # Note: Weak inequality now.
for lorg in L[r:len(L)]:
assert lorg > T
mid = (l + r) // 2
if L[mid] > T:
r = mid
else:
l = mid + 1
return r - 1 # return the first element AFTER L[r:len(L)].
(It should technically be BEFORE, I guess. If it helps all rightmost bsearches are also leftmost bsearches on the reversed array, so AFTER is secretly not wrong)[1]: https://hiandrewquinn.github.io/til-site/posts/binary-search...
Every time I needed to write something algorithmically demanding, I could do it in a day or two. Im not into Leetcoding, or competitive coding.
Most regular everyday programmers can work these things out in one or two workdays.
Its definitely not like the competitive programmers say, like if you aren't into this full time, at the time you need to write something you won't have access to time, internet and even an IDE and have to write the code in a Google doc(which needs internet connection, when I pointed this out in the interviews they didn't like it).
When do you write code that doesn't need to search? (Unless you hand it all to the database, in which case... sure, you're good)