Skip to content

Commit f7f5466

Browse files
committed
add first ture in python
1 parent 06ecabb commit f7f5466

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Binary Search/first_true.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
An array of boolean values is divided into two sections; the left section consists of all false and the
3+
right section consists of all true. Find the First True in a Sorted Boolean Array of the
4+
right section, i.e. the index of the first true element. If there is no true element, return -1.
5+
6+
Input: arr = [false, false, true, true, true]
7+
Output: 2
8+
9+
Explanation: first true's index is 2.
10+
'''
11+
def findBoundary(arr):
12+
low = 0 # Initialize the low pointer to the beginning of the list.
13+
high = len(arr) - 1 # Initialize the high pointer to the end of the list.
14+
bv = -1 # Initialize bv (boundary value) to -1.
15+
16+
while low <= high:
17+
mid = low + (high - low) // 2 # Calculate the middle index.
18+
19+
if not arr[mid]:
20+
# If the element at the middle index is 'false',
21+
# it means that the last 'true' value should be on the right side.
22+
low = mid + 1 # Move the low pointer to the right of mid.
23+
else:
24+
# If the element at the middle index is 'true',
25+
# update bv to the current middle index and continue searching on the left side.
26+
bv = mid # Update bv to the current middle index.
27+
high = mid - 1 # Move the high pointer to the left of mid.
28+
29+
# The loop ends when low > high, indicating that the search is complete.
30+
# bv contains the index of the last 'true' value encountered.
31+
return bv
32+
33+
arr = [False, False, False, True, True, True, True]
34+
boundary = findBoundary(arr)
35+
print("Boundary Index:", boundary)

0 commit comments

Comments
 (0)