Search for a Range
Question (LC.34)
Given a sorted array of integers, find the starting and ending position of a given target value.
Example
Input: [5, 7, 7, 8, 8, 10], target = 8
Output: [3, 4]Ask edge cases: if target doesn't exist in the array, return [-1, -1].
Brute Force
Linear scan. If find the target element, then extend the end index.
def searchRange(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
if n == 0:
return [-1, -1]
start_index = -1
end_index = -1
found = False
for i in range(n):
if nums[i] == target:
if not found:
found = True
start_index = i
end_index = i
else:
end_index = i
return [start_index, end_index]
This solution's performance is surprisingly good on LC.
Runtime
Memory Usage
88 ms, faster than 32.93%
15.4 MB, less than 28.87%
Analysis
Given a sorted array and we want to find a target element, that's the job of binary search. On top of that, we want to do better than linear time.
Initial thought: find first or last index then for loop to find the range. runtime will be O(log(n) + range).
On a second thought, we can just do two binary searches. 1. find the first pos 2. find the last pos
Code
Time Complexity
Runtime
Memory Usage
80 ms, faster than 84.79%
15.5 MB, less than 28.87%
Now the time complexity is only . The space complexity is also because this implementation is recursive rather than in place two pointers. I don't think logarithmic space usage is that big of a deal.
Last updated