#1375

Number of Times Binary String Is Prefix-Aligned

specialist · 630 · lc medium +30 · verified · 66% accepted · 969 likes · top 71%

Description

You have a 1-indexed binary string of length n, initially all zeros. You are given a 1-indexed array flips where step i flips bit flips[i] from 0 to 1. After step i, the string is prefix-aligned when bits 1 through i are all 1 and all remaining bits are 0. Return the number of times the string becomes prefix-aligned during the entire 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.

Code

1
2
3