Advanced · Searching · 198 of 264
First and last position
A sorted list may contain repeats. Print the first and last position (from 0) of a number, or -1 -1 when it is missing. Use binary search (or the bisect module).
Input: sorted whole numbers on one line, then the number. Output: two positions.
Examples
Input
1 2 2 2 3 4 2
Output
1 3
Input
1 1 1 1
Output
0 2
Input
1 3 5 2
Output
-1 -1
One more test checks other inputs when you press Check.
Stuck? The idea behind searching
Linear search looks at each item in turn. Binary search works on a sorted list: look at the middle, then throw away the half that can't hold the answer.
Binary search finds an item among a million in about 20 steps.
def find(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1Watch for: lo = mid instead of mid + 1 can loop for ever when two items are left.