Skip to content

Commit 724ca2e

Browse files
committed
add last occurrence algorithm
1 parent 3a65a15 commit 724ca2e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

search/last_occurrence.py

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

0 commit comments

Comments
 (0)