⚡ TL;DR
Binary search a sorted array in Python with working code. Iterative approach with O(log n) time, plus complexity analysis and interview tips.
Binary Search (#704 — Easy): Given an array of integers nums sorted in ascending order and an integer target, return the index of target in nums, or -1 if it is not present.
Problem Statement
Given an array of integers nums sorted in ascending order and an integer target, return the index of target in nums, or -1 if it is not present.
Example:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists at index 4.Approach: Iterative Two Pointers
Time: O(log n) | Space: O(1)
Keep lo and hi pointers on the search window. Compare the middle element with the target, discard the half that cannot contain it, and stop when the window closes — or the target is found.
def binary_search(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
nums = [-1, 0, 3, 5, 9, 12]
print("Index of 9:", binary_search(nums, 9))
print("Index of 2:", binary_search(nums, 2))Approach: Recursive Divide & Conquer
Time: O(log n) | Space: O(log n)
The same halving expressed as recursion: search the left or right half until the window is empty. Same comparisons, but the call stack stores log n frames.
def binary_search_recursive(nums, target, lo, hi):
if lo > hi:
return -1
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
return binary_search_recursive(nums, target, mid + 1, hi)
return binary_search_recursive(nums, target, lo, mid - 1)
nums = [-1, 0, 3, 5, 9, 12]
print("Index of 9:", binary_search_recursive(nums, 9, 0, len(nums) - 1))
print("Index of 2:", binary_search_recursive(nums, 2, 0, len(nums) - 1))Key Takeaways
- mid = (lo + hi) // 2 — integer division avoids float indices in every language
- The loop condition lo <= hi (not <) is the classic off-by-one trap
- Halving the window each step is what turns 1,000,000 elements into ~20 comparisons
FAQ
What is the best approach to solve Binary Search in Python?
The recommended approach is Iterative Two Pointers, which runs in O(log n) time with O(1) space. The full Python implementation is shown above.
What is the time complexity of Binary Search in Python?
Using Iterative Two Pointers, the time complexity is O(log n) and the space complexity is O(1); Recursive Divide & Conquer runs in O(log n) time with O(log n) space.
Happy coding!

Written by Mihir Pipermitwala
Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.
More about Mihir →