Left right pointers
- Algorithms course
- Beginner
- Lesson 54/80
- 4 min
Narrow the range with low and high pointers.
Left right pointers
Binary search defines the search range with left and right pointers. Initially left=0, right=n-1.
At each step, the middle is computed: mid = (left + right) // 2. Depending on the target, left or right is updated.
Range update
If the target is greater than arr[mid], left = mid + 1: search the right half. If smaller, right = mid - 1: search the left half.
Adding +1 and -1 prevents mid from being checked again. This is important to avoid infinite loops.
Practice Find mid
Write find_mid(left, right). Return the middle index. Print 4 with print(find_mid(0, 9)).
Starter code
def find_mid(left, right):
# Middle indexSample solution
def find_mid(left, right):
# Middle index
return (left + right) // 2
print(find_mid(0, 9))Expected output
4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Mid computation
mid = (left + ____) // 2
mid = (left + right) // 2
Explanation: right is right.
2 Left right pointers: match the terms
| Term | Meaning |
|---|---|
left |
Left |
right |
Right |
mid |
Middle |
left <= right |
Loop condition |
3 What if target is greater than arr[mid]?
- return mid
- return -1
- right = mid - 1
- left = mid + 1 Correct answer
Explanation: left = mid + 1 is set.