Skip to the solution
EasyDSA9 min read

How does binary search work and what are its requirements?

1.1k views

The problem

Question presented to candidate: "How does binary search work, and what has to be true about the data for it to work? Please write it in Python and tell me its complexity."

What a strong answer should cover:

  • The mechanism: keep lo and hi, check the middle, discard the half that cannot contain the target; stop when found or the range is empty.
  • The requirements: sorted (or monotonic) data, O(1) random access, known bounds and a consistent comparison โ€” and why a linked list does not qualify.
  • O(log n) time with a concrete number (about 20 steps for a million items), O(1) space iteratively.
  • Handles duplicates with lower and upper bound, and states the loop invariant to avoid off-by-one errors.
  • Python specifics: // for the midpoint, ints never overflow, and the bisect module (bisect_left, bisect_right, insort).

Code / implementation expected: Yes โ€” a correct iterative binary search in Python, ideally also the lower-bound variant.

  • binary-search

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonClassic binary search with a trace and step counts
PythonLower bound, upper bound, first and last occurrence
PythonThe standard library way, and midpoint overflow

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 3 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you solve the climbing stairs problem?

Continue