Skip to content

Commit 5596842

Browse files
committed
add first occurrence algorithm
1 parent 4d0309c commit 5596842

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

search/first_occurrence.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
first_occurrence([2, 2, 2, 3, 3, 4, 4, 5, 5, 5], 3) => 3
3+
first_occurrence([2, 2, 2, 3, 3, 4, 4, 5, 5, 5], 2) => 0
4+
complexity: O(log n)
5+
"""
6+
7+
from typing import Any
8+
9+
10+
def first_occurrence(array: list, target: Any) -> int:
11+
low, high = 0, len(array) - 1
12+
while low < high:
13+
middle = (low + high) // 2
14+
if array[middle] < target:
15+
low = middle + 1
16+
else: # when target <= array[middle]
17+
high = middle - 1
18+
if array[low] == target:
19+
return low
20+
return None
21+
22+
23+
if __name__ == "__main__":
24+
print(first_occurrence([2, 2, 2, 3, 3, 4, 4, 5, 5, 5], 3) == 3)
25+
print(first_occurrence([2, 2, 2, 3, 3, 4, 4, 5, 5, 5], 2) == 0)

0 commit comments

Comments
 (0)