
Sponsored
Sponsored
The goal is to use the binary search algorithm to achieve O(log n) time complexity. We perform two separate binary searches:
Time Complexity: O(log n) due to binary search. Space Complexity: O(1) as no extra space is used apart from input and output.
1class Solution:
2 def searchRange(self, nums, target):
3 def findFirst(nums, target):
4 left, right = 0, len(nums) - 1
5 result = -1
6 while left <= right:
7 mid = left + (right - left) // 2
8 if nums[mid] >= target:
9 if nums[mid] == target:
10 result = mid
11 right = mid - 1
12 else:
13 left = mid + 1
14 return result
15
16 def findLast(nums, target):
17 left, right = 0, len(nums) - 1
18 result = -1
19 while left <= right:
20 mid = left + (right - left) // 2
21 if nums[mid] <= target:
22 if nums[mid] == target:
23 result = mid
24 left = mid + 1
25 else:
26 right = mid - 1
27 return result
28
29 return [findFirst(nums, target), findLast(nums, target)]The Python solution provides two inner functions for finding the first and last position of the target value, ensuring the binary search achieves an efficient time complexity.