A sorted list is given. Find the position where a target is, or where it would be inserted to keep the list sorted.
What to build
A program that finds the leftmost insertion position of a target in a sorted list, in O(log n).
Requirements
- If the target is in the list, print the position of its first occurrence.
- Otherwise print the position where it would be inserted.
- Use binary search, not a scan.
Input
The first line has n and target. The second line has the n numbers in non-decreasing order.
Output
The position (from 0).
Constraints
1 ≤ n ≤ 10⁵.
Example
Input:
4 5
1 3 5 6
Output:
2
Why it works
The test nums[i] ≥ target is False for small positions and True from some point on, so halving the range finds the first True position, which is exactly the leftmost place for the target.
Examples
4 5 1 3 5 6
2
4 2 1 3 5 6
1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
This is the smallest index i with nums[i] ≥ target, found by binary search.
Hint 2
If the middle value is at least the target, keep it: high = mid. Otherwise low = mid + 1.
Hint 3
The range is 0 to n, because the target may go after every number.
Solution
Show one correct solution (try it yourself first)
n, target = map(int, input().split())
nums = list(map(int, input().split()))
low, high = 0, n
while low < high:
mid = (low + high) // 2
if nums[mid] >= target:
high = mid
else:
low = mid + 1
print(low)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step