Skip to content

Commit 775881b

Browse files
author
Joseph Luce
authored
Create 34_find_first_and_last_position_of_element_in_sorted_array.md
1 parent 09fd19c commit 775881b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# 34. Find First and Last Position of Element in Sorted Array
2+
3+
## Iterative binary search solution
4+
- Runtime: O(log(N))
5+
- Space: O(1)
6+
- N = Number of elements in array
7+
8+
Knowing how to write a binary search whether iteratively or recursively is a must.
9+
However, there is a second thing being tested, whether you follow DRY (Don't repeat yourself).
10+
11+
```
12+
class Solution:
13+
def searchRange(self, nums: List[int], target: int) -> List[int]:
14+
left_most_index = self.get_left_or_right_most_index(nums, target)
15+
right_most_index = self.get_left_or_right_most_index(nums, target, search_left=False)
16+
return [left_most_index, right_most_index]
17+
18+
def get_left_or_right_most_index(self, nums, target, search_left=True):
19+
left, right = 0, len(nums)-1
20+
result_index = None
21+
while left <= right:
22+
mid = left + ((right - left)//2)
23+
if nums[mid] == target:
24+
result_index = mid
25+
if search_left: # get left most index
26+
if nums[mid] < target: # go right
27+
left = mid+1
28+
else: # go left
29+
right = mid-1
30+
else: # get right most index
31+
if nums[mid] > target: # go left
32+
right = mid-1
33+
else: # go right
34+
left = mid+1
35+
return result_index if result_index is not None else -1
36+
```

0 commit comments

Comments
 (0)