You have a 1-indexed binary string of length n where all the bits are
0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array
flips where flips[i] indicates that the bit at index i will be flipped in the ith step.
A binary string is prefix-aligned if, after the ith step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros.
Return the number of times the binary string isprefix-aligned during the flipping process.
Input: flips =[3,2,4,1,5]Output: 2Explanation: The binary string is initially "00000".After applying step 1: The string becomes "00100", which is not prefix-aligned.After applying step 2: The string becomes "01100", which is not prefix-aligned.After applying step 3: The string becomes "01110", which is not prefix-aligned.After applying step 4: The string becomes "11110", which is prefix-aligned.After applying step 5: The string becomes "11111", which is prefix-aligned.We can see that the string was prefix-aligned 2 times, so we return2.
Input: flips =[4,1,2,3]Output: 1Explanation: The binary string is initially "0000".After applying step 1: The string becomes "0001", which is not prefix-aligned.After applying step 2: The string becomes "1001", which is not prefix-aligned.After applying step 3: The string becomes "1101", which is not prefix-aligned.After applying step 4: The string becomes "1111", which is prefix-aligned.We can see that the string was prefix-aligned 1 time, so we return1.
If after i steps, the maximum flipped position is i, then all positions 1..i have been flipped, so the prefix is aligned. We can track the max position after each step and count how many times max == i.
classSolution {
public:int numTimesAllBlue(vector<int>& flips) {
int ans =0, max_pos =0;
for (int i =0; i < flips.size(); ++i) {
max_pos = max(max_pos, flips[i]);
if (max_pos == i+1) ans++;
}
return ans;
}
};
1
2
3
4
5
6
7
8
funcnumTimesAllBlue(flips []int) int {
ans, maxPos:=0, 0fori, f:=rangeflips {
iff > maxPos { maxPos = f }
ifmaxPos==i+1 { ans++ }
}
returnans}
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintnumTimesAllBlue(int[] flips) {
int ans = 0, maxPos = 0;
for (int i = 0; i < flips.length; i++) {
maxPos = Math.max(maxPos, flips[i]);
if (maxPos == i+1) ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funnumTimesAllBlue(flips: IntArray): Int {
var ans = 0var maxPos = 0for (i in flips.indices) {
maxPos = maxOf(maxPos, flips[i])
if (maxPos == i+1) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
defnumTimesAllBlue(self, flips: list[int]) -> int:
ans = max_pos =0for i, f in enumerate(flips):
max_pos = max(max_pos, f)
if max_pos == i+1:
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnnum_times_all_blue(flips: Vec<i32>) -> i32 {
letmut ans =0;
letmut max_pos =0;
for (i, &f) in flips.iter().enumerate() {
max_pos = max_pos.max(f asusize);
if max_pos == i+1 { ans +=1; }
}
ans
}
}