Imagine you're controlling a row of smart light switches that start in the OFF position. You have a special remote control that can turn ON switches in a specific sequence, but here's the catch: you can't choose which switch to turn on next — the sequence is predetermined!
You start with a binary string of length n where all bits are initially 0 (switches OFF). You're given a 1-indexed array flips where flips[i] tells you which switch position to turn ON during the i-th step.
A configuration is called "prefix-aligned" when, after step i, the first i switches are all ON (positions 1 through i are all 1s) and all remaining switches are OFF (all 0s).
Goal: Count how many times during the entire flipping process the switches become prefix-aligned.
Example: If flips = [3,2,4,1,5] and n = 5:
• Step 1: Turn ON position 3 → 00100 (not prefix-aligned)
• Step 2: Turn ON position 2 → 01100 (not prefix-aligned)
• Step 3: Turn ON position 4 → 01110 (not prefix-aligned)
• Step 4: Turn ON position 1 → 11110 (prefix-aligned! First 4 positions are 1111)
• Step 5: Turn ON position 5 → 11111 (prefix-aligned! All 5 positions are 11111)
Answer: 2 times prefix-aligned.
Input & Output
Visualization
Time & Space Complexity
Single pass through the flips array, constant time operations per step
Only using a few variables to track maximum position and counter
Constraints
- n == flips.length
- 1 ≤ n ≤ 5 × 104
- flips is a permutation of the integers in the range [1, n]
- All flip positions are 1-indexed