Skip to content

Commit 017acc8

Browse files
committed
Add Python solutions for Search Insert Position and Search Range
1 parent 788d95b commit 017acc8

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from typing import List
2+
3+
def search_insert(nums: List[int], target: int) -> int:
4+
"""
5+
Finds the index to insert a target value into a sorted list.
6+
7+
If the target is found, its index is returned. Otherwise, returns the
8+
index where it would be if it were inserted in order.
9+
10+
Args:
11+
nums: A sorted list of integers.
12+
target: The integer to search for.
13+
14+
Returns:
15+
The index for the target value.
16+
"""
17+
left, right = 0, len(nums) - 1
18+
19+
while left <= right:
20+
mid = (left + right) // 2
21+
if nums[mid] == target:
22+
return mid
23+
elif nums[mid] < target:
24+
left = mid + 1
25+
else:
26+
right = mid - 1
27+
return left
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from typing import List
2+
3+
def search_range(nums: List[int], target: int) -> List[int]:
4+
"""
5+
Finds the first and last position of a given target value in a sorted array.
6+
7+
Args:
8+
nums: A sorted list of integers.
9+
target: The integer to search for.
10+
11+
Returns:
12+
A list containing the starting and ending index of the target.
13+
Returns [-1, -1] if the target is not found.
14+
"""
15+
16+
def find_bound(is_first: bool) -> int:
17+
"""Helper to find the leftmost or rightmost occurrence of the target."""
18+
left, right = 0, len(nums) - 1
19+
bound = -1
20+
while left <= right:
21+
mid = (left + right) // 2
22+
if nums[mid] == target:
23+
bound = mid
24+
if is_first:
25+
right = mid - 1 # Continue searching on the left
26+
else:
27+
left = mid + 1 # Continue searching on the right
28+
elif nums[mid] < target:
29+
left = mid + 1
30+
else:
31+
right = mid - 1
32+
return bound
33+
34+
first_bound = find_bound(True)
35+
if first_bound == -1:
36+
return [-1, -1]
37+
38+
last_bound = find_bound(False)
39+
return [first_bound, last_bound]

0 commit comments

Comments
 (0)