LeetCode #34 Find First and Last Position of Element in Sorted Array

Problem

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Examples

1
2
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
1
2
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Solution1

Method: Binary Search with left_flag

Time Complexity: O(log n)

Space Complexity: O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
def binarySearch(nums, target, left_flag):
if not nums:
return -1

left = 0
right = len(nums) - 1
found = False
target_idx = -1

while left < right:
mid = (right + left) // 2
if nums[mid] == target:
target_idx = mid
if left_flag == True:
right = mid
else:
left = mid + 1
else:
if nums[mid] > target:
right = mid
else:
left = mid + 1

if nums[right] == target:
return right
else:
return target_idx

return [binarySearch(nums, target, True), binarySearch(nums, target, False)]

Solution2

Method: Two Binary Search

Time Complexity: O(log n)

Space Complexity: O(log n)

1
2
3
4
5
6
7
8
9
10
11
12
def searchRange(self, nums, target):
def search(n):
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) / 2
if nums[mid] >= n:
hi = mid
else:
lo = mid + 1
return lo
lo = search(target)
return [lo, search(target+1)-1] if target in nums[lo:lo+1] else [-1, -1]

Solution3

Method: Built-in bisect

Time Complexity: O(log n)

Space Complexity: O(log n)

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lo = bisect.bisect_left(nums, target)

return [lo, bisect.bisect(nums, target)-1] \
if target in nums[lo:lo+1] else [-1, -1]