What about this version? from typing import List def searchRange(nums: List[int],…
- User
What about this version?
from typing import List
def searchRange(nums: List[int], target: int) -> List[int]: """ Returns the starting and ending index of
targetin a sorted listnums. Iftargetis not present, returns [-1, -1].The algorithm runs in O(log n) time by performing two binary searches: * one to locate the left‑most occurrence, * one to locate the right‑most occurrence. """ # ---------- helper: leftmost index ---------- def binary_search_left(arr: List[int], tgt: int) -> int: left, right = 0, len(arr) - 1 while left <= right: # Use integer division (//) – the original code used `/` which # yields a float and cannot be used as a list index. mid = left + (right - left) // 2 if arr[mid] < tgt: left = mid + 1 # target must be to the right else: right = mid - 1 # could be at mid or left of it return left # first index where arr[idx] >= tgt # ---------- helper: rightmost index ---------- def binary_search_right(arr: List[int], tgt: int) -> int: left, right = 0, len(arr) - 1 while left <= right: mid = left + (right - left) // 2 if arr[mid] <= tgt: left = mid + 1 # target could be at mid or right of it else: right = mid - 1 return right # last index where arr[idx] <= tgt # ---- main logic ------------------------------------------------- start = binary_search_left(nums, target) end = binary_search_right(nums, target) # The binary‑search helpers give us the *candidate* boundaries. # We must verify that they really point to `target`, otherwise the # element is absent. if start < len(nums) and end >= 0 and start <= end and nums[start] == target and nums[end] == target: return [start, end] else: return [-1, -1] Assistant
The provided code is correct and handles all edge cases appropriately. Here's a breakdown of its functionality and why it works:
Key Components:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.