—
Find the first matching index by binary search
Tutor me on https://mlprep.iwase.dev/item/prog-ds-first-binary-search/. This is a screening item. If window.mlPrepAgent is available, read attempts for item prog-ds-first-binary-search before tutoring. Inspect my attempt, keep the item ID, and do not reveal the full answer first. After a real attempt, append its record with recorded_by agent, include agent_session_id when available, and read it back.Problem
Implement first_index(nums, target) for a list sorted in nondecreasing
order. Return the first index containing target, including among
duplicates, or -1 when absent. Use comparisons.
Reveal answer or reference solution
Search the half-open interval [lo, hi) for the first position whose
value is not less than the target. Move lo past values below the target;
otherwise move hi to mid. Validate the final candidate before
returning it.
def first_index(nums: list[int], target: int) -> int:
lo = 0
hi = len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
if lo < len(nums) and nums[lo] == target:
return lo
return -1Public tests
first_index([], 3)→-1first_index([1, 2, 2, 2, 5], 2)→1first_index([1, 2, 2, 2, 5], 4)→-1first_index([1], 1)→0first_index([1, 3, 5], 1)→0
Previous attempts
Loading attempts saved in this browser…