Number of Times Binary String Is Prefix-Aligned Problem
Description
LeetCode Problem 1375.
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 flips[i] will be flipped in the i^th step.
A binary string is prefix-aligned 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 prefix-aligned 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 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 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 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 return 1.
Constraints:
n == flips.length1 <= n <= 5 * 10^4flipsis a permutation of the integers in the range[1, n].
Solution
Approach: Track the Largest Flipped Index
After step i, exactly i different bits are on, because flips is a permutation and no bit is flipped twice. The string is prefix-aligned when those i bits are exactly bits 1 to i.
That happens exactly when the largest index flipped so far equals i: if all i flipped indexes are at most i, and they are i different numbers, they must be 1, 2, ..., i. If any of them is larger than i, some bit outside the prefix is on.
So walk through flips, keep the running maximum, and count the steps where the maximum equals the step number. In Example 1, [3,2,4,1,5], the running maximum is 3, 3, 4, 4, 5, which matches the step number at steps 4 and 5, so the answer is 2.
Complexity: O(n) time and O(1) extra space.
class Solution:
def numTimesAllBlue(self, flips: List[int]) -> int:
count = highest = 0
for i, x in enumerate(flips, 1):
highest = max(highest, x) # highest index flipped so far
# i distinct bits are on, all of them <= i: they must be exactly bits 1..i.
if highest == i:
count += 1
return count