1375. Number of Times Binary String Is PrefixAligned
Description
You have a 1indexed 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 1indexed integer array flips
where flips[i]
indicates that the bit at index i
will be flipped in the i^{th}
step.
A binary string is prefixaligned if, after the i^{th}
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 is prefixaligned during the flipping process.
Example 1:
Input: flips = [3,2,4,1,5] Output: 2 Explanation: The binary string is initially "00000". After applying step 1: The string becomes "00100", which is not prefixaligned. After applying step 2: The string becomes "01100", which is not prefixaligned. After applying step 3: The string becomes "01110", which is not prefixaligned. After applying step 4: The string becomes "11110", which is prefixaligned. After applying step 5: The string becomes "11111", which is prefixaligned. We can see that the string was prefixaligned 2 times, so we return 2.
Example 2:
Input: flips = [4,1,2,3] Output: 1 Explanation: The binary string is initially "0000". After applying step 1: The string becomes "0001", which is not prefixaligned. After applying step 2: The string becomes "1001", which is not prefixaligned. After applying step 3: The string becomes "1101", which is not prefixaligned. After applying step 4: The string becomes "1111", which is prefixaligned. We can see that the string was prefixaligned 1 time, so we return 1.
Constraints:
n == flips.length
1 <= n <= 5 * 10^{4}
flips
is a permutation of the integers in the range[1, n]
.
Solutions
Solution 1: Direct Traversal
We can traverse the array $flips$, keeping track of the maximum value $mx$ of the elements we have traversed so far. If $mx$ equals the current index $i$ we are traversing, it means that the first $i$ elements have all been flipped, i.e., the prefix is consistent, and we increment the answer.
After the traversal is finished, we return the answer.
The time complexity is $O(n)$, where $n$ is the length of the array $flips$. The space complexity is $O(1)$.









