|
| 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