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: 1
💡 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. Only 1 prefix-aligned state.
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 Alignment ProblemInput: flips = [3,2,4,1,5]Initial State[0,0,0,0,0]Flip ProcessStep by StepCheck AlignmentCount Valid StatesStep 1: flip 3 → [0,0,1,0,0]Check [1]: need 1 but have 0 ✗Step 2: flip 2 → [0,1,1,0,0]Check [1,2]: need 1,1 but have 0,1 ✗Step 4: flip 1 → [1,1,1,1,0]Check [1,2,3,4]: all are 1 ✓Result: 1 prefix-aligned state foundKey: max flipped position = current step number
Understanding the Visualization
1
Input
Array of flip positions in order
2
Process
Track when all positions [1,i] are ones
3
Output
Count of prefix-aligned states
Key Takeaway
🎯 Key Insight: Prefix-aligned when maximum flipped position equals current step
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