When does an O(log n) algorithm beat an O(n) one, and how would you demonstrate that with code?
An O(log n) algorithm wins whenever it can repeatedly discard half of the remaining candidates instead of testing them one by one. That requires a strong extra condition: the data must be sorted, or at least ordered in a way that a comparison can rule out a whole half of the possibilities. Without that structure, no amount of cleverness lets you skip candidates, and the linear scan is genuinely the best you can do.
def linear_search(items, target):
for i, value in enumerate(items):
if value == target:
return i
return -1
def binary_search(items, target):
low, high = 0, len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
if items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
data = list(range(0, 1000, 2))
print(linear_search(data, 500), binary_search(data, 500))Both print 250, so they agree on the answer. They disagree on effort: the linear version may inspect up to 500 elements, while the binary version never needs more than ten probes because each step halves the search interval. Multiplying the input by a thousand multiplies the linear cost by a thousand and the binary cost by about ten.
The trade-off to state is that the logarithmic win is bought with a precondition. Sorting is itself O(n log n) or better, so for a single lookup on unsorted data, a linear scan wins overall. The moment you need many lookups on the same data, paying the sort once and then doing logarithmic lookups is the cheaper deal. That is the real trade-off an interviewer is listening for: the algorithm is only as good as the structure you maintain to feed it.