Binary Search Iterative Approach in DSA Python - Time & Space Complexity
We want to understand how the time taken by binary search changes as the list size grows.
Specifically, how many steps does it take to find a number in a sorted list?
Analyze the time complexity of the following code snippet.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
This code searches for a target value in a sorted list by repeatedly dividing the search range in half.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that halves the search range each time.
- How many times: The loop runs until the search range is empty, roughly halving the range each step.
Each step cuts the list size roughly in half, so the number of steps grows slowly as the list gets bigger.
| Input Size (n) | Approx. Operations (loop iterations) |
|---|---|
| 10 | About 4 |
| 100 | About 7 |
| 1000 | About 10 |
Pattern observation: Doubling the input size adds only one more step.
Time Complexity: O(log n)
This means the time grows slowly, increasing by one step each time the input size doubles.
[X] Wrong: "Binary search checks every element one by one, so it is O(n)."
[OK] Correct: Binary search does not check every element; it cuts the search space in half each time, so it takes far fewer steps than checking all elements.
Understanding binary search time complexity shows you can analyze efficient algorithms, a key skill in problem solving and coding interviews.
"What if the list was not sorted? How would the time complexity of searching change?"
Practice
mid variable in the iterative binary search algorithm?Solution
Step 1: Understand the role of
Themidin binary searchmidvariable calculates the middle index between the current low and high indices to split the search range.Step 2: Explain why
By checking the element atmidis importantmid, the algorithm decides whether to search the left or right half next.Final Answer:
To find the middle index of the current search range -> Option CQuick Check:
mid= middle index [OK]
- Confusing
midwith the target value - Using
midas a counter instead of index - Not updating
midinside the loop
mid in an iterative binary search in Python?Solution
Step 1: Identify correct integer division in Python
In Python,//performs integer division, which is needed for an index.Step 2: Explain why
/is incorrect/returns a float, which cannot be used as a list index.Final Answer:
mid = (low + high) // 2 -> Option AQuick Check:
Use integer division for index [OK]
- Using / which returns float
- Adding low and high without division
- Incorrect operator precedence without parentheses
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
arr = [2, 4, 6, 8, 10]
print(binary_search(arr, 6))Solution
Step 1: Trace the binary search for target 6
Initial low=0, high=4, mid=2. arr[2]=6 matches target.Step 2: Return the index where target is found
Since arr[mid] == target, function returns 2 immediately.Final Answer:
2 -> Option DQuick Check:
Index of 6 in array is 2 [OK]
- Confusing index with value
- Returning value instead of index
- Off-by-one errors in mid calculation
def binary_search(arr, target):
low = 0
high = len(arr)
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1Solution
Step 1: Check initialization of high
High is set to len(arr), which is out of valid index range (0 to len(arr)-1).Step 2: Explain correct initialization
High should be len(arr) - 1 to avoid index out of range errors when accessing arr[mid].Final Answer:
high should be initialized as len(arr) - 1 -> Option AQuick Check:
High = len(arr) - 1 for valid index [OK]
- Setting high to len(arr) causes index error
- Changing low start incorrectly
- Using float division for mid
arr = [1, 3, 5, 7, 9, 11, 13], how many iterations will the iterative binary search take to find the target 7?Solution
Step 1: Trace iterations to find 7
Iteration 1: low=0, high=6, mid=3, arr[3]=7 matches target.Step 2: Count iterations
Since target found at first mid check, total iterations = 1.Step 3: Reconsider counting loop passes
Loop runs once, but mid calculation and comparison count as one iteration.Final Answer:
1 -> Option BQuick Check:
Target found at first mid check [OK]
- Counting iterations incorrectly
- Assuming always 3 iterations for 7 elements
- Confusing iterations with index value
Ready to prove it?
Pass the test and this pattern moves unknown
