Back to Practice
#0033
Binary Search
EasyDSA16 min10 XP
Problem
Given a sorted list nums and a target, return the target index if found. Return -1 otherwise.
Why This Matters
Binary search is the first algorithm where correctness depends on carefully maintained boundaries.
Function Signature
def binary_search(nums, target):
Examples
Example 1
Inputnums = [1, 3, 5, 7, 9], target = 7
Output3
The value 7 is at index 3.
Constraints
- nums is sorted ascending.
- Return -1 if target is missing.
- Use O(log n) search.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 4 hidden categories
Found target
Input[1, 3, 5, 7, 9], 7
Expected3
Binary search narrows until index 3 is found.
Missing target
Input[1, 3, 5, 7, 9], 4
Expected-1
The search range becomes empty.
Hidden Test Categories
Empty listSingle element foundSingle element missingTarget at first or last index