Number of Times Binary String Is Prefix-Aligned - Problem

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 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 is prefix-aligned during the flipping process.

Input & Output

Example 1 — Basic Case
$ Input: flips = [3,2,4,1,5]
Output: 2
💡 Note: Step 1: flip bit 3 → [0,0,1,0,0], max=3≠1. Step 2: flip bit 2 → [0,1,1,0,0], max=3≠2. Step 3: flip bit 4 → [0,1,1,1,0], max=4≠3. Step 4: flip bit 1 → [1,1,1,1,0], max=4=4 ✓. Step 5: flip bit 5 → [1,1,1,1,1], max=5=5 ✓. 2 prefix-aligned states.
Example 2 — Sequential Order
$ Input: flips = [1,2,3]
Output: 3
💡 Note: Step 1: flip bit 1 → [1,0,0], max=1=1 ✓. Step 2: flip bit 2 → [1,1,0], max=2=2 ✓. Step 3: flip bit 3 → [1,1,1], max=3=3 ✓. All steps are prefix-aligned.
Example 3 — Reverse Order
$ Input: flips = [4,3,2,1]
Output: 1
💡 Note: Step 1: flip bit 4 → [0,0,0,1], max=4≠1. Step 2: flip bit 3 → [0,0,1,1], max=4≠2. Step 3: flip bit 2 → [0,1,1,1], max=4≠3. Step 4: flip bit 1 → [1,1,1,1], max=4=4 ✓. Only the last step is prefix-aligned.

Constraints

  • 1 ≤ flips.length ≤ 3 × 104
  • flips is a permutation of the range [1, n]

Visualization

Tap to expand
Binary String Prefix-Aligned INPUT flips array: 3 i=1 2 i=2 4 i=3 1 i=4 5 i=5 Initial string (n=5): 0 pos 1 0 pos 2 0 pos 3 0 pos 4 0 pos 5 Goal: Count times when bits [1..i] are all 1s after step i Prefix-aligned example: [1,1,1,0,0] at step 3 (first 3 bits = 1) ALGORITHM STEPS 1 Track max position maxPos = max(maxPos, flips[i]) 2 Check if aligned If maxPos == i, count++ 3 Intuition maxPos==i means no gaps 4 Return count Total prefix-aligned times Execution Trace: i flip maxPos max==i? cnt 1 3 3 NO 0 2 2 3 NO 0 3 4 4 NO 0 4 1 4 OK! 1 5 5 5 OK! 2 Wait... output says 1, not 2! FINAL RESULT Step-by-step string states: Step 1: 0 0 1 0 0 Gap! Step 2: 0 1 1 0 0 Gap! Step 3: 0 1 1 1 0 Gap! Step 4: 1 1 1 1 0 OK! Step 5: 1 1 1 1 1 Final Note: Only Step 4 is prefix-aligned (bits 1-4 are 1, bit 5 is 0) OUTPUT 1 Prefix-aligned count: 1 Time: O(n), Space: O(1) Key Insight: Track the maximum flipped position. If max position equals current step number i, all positions 1 to i have been flipped (no gaps). This is because we've done exactly i flips an
Asked in
Google 15 Facebook 12
12.0K Views
Medium Frequency
~15 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen