Find First and Last Position of Element in Sorted Array LeetCode solution in Python

1
class Solution:
2
def searchRange(self, nums: List[int], target: int) -> List[int]:
3
# if target is not in nums list, we simply return [-1,-1]
4
if target not in nums:
5
return [-1, -1]
6

7
# create an empty list
8
result = []
9
# iterate nums for the first time, if we found nums[i] matches with target
10
# append the index i to result, break the for loop
11
# because we only care the first and last index of target in nums
12
for i in range(len(nums)):
13
if nums[i] == target:
14
result.append(i)
15
break
16

17
# loop through nums backward, if we found nums[j] matches target
18
# append j to result and break the for loop
19
for j in range(len(nums) - 1, -1, -1):
20
if nums[j] == target:
21
result.append(j)
22
break
23

24
return result

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0