Binary Search in Python — Python Technical Interview Questions & Answers
Binary Search in Python
Binary Search in Python
- Binary search cuts a sorted list in half each time. Look at the middle. Too small? Search the right half. Too big? Left half. About log n steps — O(log n). First sentence in the viva: the list must be sorted. Unsorted binary search is wrong, not “almost right”.
- Trace [1, 2, 3, 4, 5] looking for 4: mid 3, go right, find 4. State the sorted precondition before you write a line of code.
- Binary Search in Python — output: 3. 12 is at index 3. Unsorted list would be wrong — sort first.
Technical Interview Tip: Sorted requirement is mandatory.
Code Examples for Binary Search in Python
Example
# Binary search
a = [2, 5, 8, 12, 20]
key = 12
lo, hi = 0, len(a) - 1
ans = -1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == key:
ans = mid
break
if a[mid] < key:
lo = mid + 1
else:
hi = mid - 1
print(ans)
Binary Search in Python — output: 3. 12 is at index 3. Unsorted list would be wrong — sort first.
How to Explain Binary Search in Python to an Interviewer
Explain Binary Search as if you are teaching a junior — definition, then one tiny script.
Halve a sorted list. Must be sorted. O(log n).
What does the example print, and why?
Binary Search in Python — output: 3
What mistake do freshers make with Binary Search?
Binary on unsorted data.