Skip to content

Commit bd96069

Browse files
authored
Merge pull request #1696 from akgmage/dev
Dev
2 parents 0befdcc + 1790298 commit bd96069

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Binary Search/first_true.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
public import java.util.Arrays;
12+
import java.util.List;
13+
import java.util.Scanner;
14+
import java.util.stream.Collectors;
15+
16+
class Solution {
17+
public static int findBoundary(List<Boolean> arr) {
18+
int low = 0; // Initialize the low pointer to the beginning of the list.
19+
int high = arr.size() - 1; // Initialize the high pointer to the end of the list.
20+
int bv = -1; // Initialize bv (boundary value) to -1.
21+
22+
while (low <= high) {
23+
int mid = low + (high - low) / 2; // Calculate the middle index.
24+
25+
if (arr.get(mid) == false) {
26+
// If the element at the middle index is 'false',
27+
// it means that the last 'true' value should be on the right side.
28+
low = mid + 1; // Move the low pointer to the right of mid.
29+
} else {
30+
// If the element at the middle index is 'true',
31+
// update bv to the current middle index and continue searching on the left side.
32+
bv = mid; // Update bv to the current middle index.
33+
high = mid - 1; // Move the high pointer to the left of mid.
34+
}
35+
}
36+
37+
// The loop ends when low > high, indicating that the search is complete.
38+
// bv contains the index of the last 'true' value encountered.
39+
return bv;
40+
}
41+
}

0 commit comments

Comments
 (0)