Skip to content

Instantly share code, notes, and snippets.

@toritsejuFO
Last active April 25, 2021 16:02
Show Gist options
  • Save toritsejuFO/3dfd21683f8a9067ef3bcb3c4b085a6f to your computer and use it in GitHub Desktop.
Save toritsejuFO/3dfd21683f8a9067ef3bcb3c4b085a6f to your computer and use it in GitHub Desktop.
def binary_search(sorted_nums, val, minimum, maximum):
if maximum < minimum:
return -1
mid = minimum + ((maximum - minimum) // 2)
if val == sorted_nums[mid]:
return mid
elif val < sorted_nums[mid]:
return binary_search(sorted_nums, val, minimum, mid - 1)
else:
return binary_search(sorted_nums, val, mid + 1, maximum)
def find_start_and_end_pos_of_val(nums, val):
start = end = -1
if nums == None or len(nums) == 0 or type(val) != int:
return [start, end]
sorted_nums = sorted(nums)
val_index = binary_search(sorted_nums, val, 0, len(sorted_nums) - 1)
if val_index == -1:
return [start, end]
start = end = val_index
# Loop through downwards from the index below the value index
for i in range(val_index - 1, -1, -1):
if val == sorted_nums[i]:
start = i
else: break
# Loop through upwards from the index above the value index
for i in range(val_index + 1, len(sorted_nums)):
if val == sorted_nums[i]:
end = i
else: break
return [start, end]
if __name__ == '__main__':
nums = [0, 8, -2, 5, 0]
val = 0
retval = find_start_and_end_pos_of_val(nums, val)
print(retval)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment