|
| 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 | +function findBoundary(arr) { |
| 12 | + let low = 0; // Initialize the low pointer to the beginning of the array. |
| 13 | + let high = arr.length - 1; // Initialize the high pointer to the end of the array. |
| 14 | + let bv = -1; // Initialize bv (boundary value) to -1. |
| 15 | + |
| 16 | + while (low <= high) { |
| 17 | + let mid = low + Math.floor((high - low) / 2); // Calculate the middle index. |
| 18 | + |
| 19 | + if (!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 | + } |
| 30 | + |
| 31 | + // The loop ends when low > high, indicating that the search is complete. |
| 32 | + // bv contains the index of the last 'true' value encountered. |
| 33 | + return bv; |
| 34 | +} |
| 35 | + |
| 36 | +const arr = [false, false, false, true, true, true, true]; |
| 37 | +const boundary = findBoundary(arr); |
| 38 | +console.log("Boundary Index:", boundary); |
0 commit comments