January 7, 2025
We're working through binary search problems. This one has an initial solution with many lines duplicated. We further work the solution to use a function and a boolean variable to make the code more clean via the DRY principle.
1class Solution:2 def searchRange(self, nums: List[int], target: int) -> List[int]:34 start, end = 0, len(nums) - 15 result = [-1, -1]6 while start <= end:7 mid = start + (end - start) // 28 left = nums[mid - 1] if mid > 0 else float('-inf')9 if nums[mid] == target:10 if left != target:11 result[0] = mid12 break13 end = mid - 114 elif nums[mid] < target:15 start = mid + 116 else:17 end = mid - 118 start, end = 0, len(nums) - 119 while start <= end:20 mid = start + (end - start) // 221 right = nums[mid + 1] if mid < len(nums) - 1 else float('inf')22 if nums[mid] == target:23 if right != target:24 result[1] = mid25 break26 start = mid + 127 elif nums[mid] < target:28 start = mid + 129 else:30 end = mid - 131 return result
Time complexity is O(logn) and space complexity is O(1).
LeetCode 207. Course Schedule
LeetCode 120. Triangle