#1375
Number of Times Binary String Is Prefix-Aligned
MediumArrayArrayGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of checking the prefix after each flip, we can keep track of the maximum index flipped so far and compare it to the current step. If they match, it means all previous bits are aligned.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to keep track of the maximum index flipped so far.
- 2Step 2: For each flip in the flips array, update the maximum index flipped.
- 3Step 3: If the maximum index flipped equals the current step index (1-indexed), increment the count of prefix-aligned occurrences.
solution.py8 lines
1def countPrefixAligned(flips):
2 max_flipped = 0
3 count = 0
4 for i in range(len(flips)):
5 max_flipped = max(max_flipped, flips[i])
6 if max_flipped == i + 1:
7 count += 1
8 return countℹ
Complexity note: The time complexity is O(n) because we only iterate through the flips array once, and we use constant space for our variables.
- 1The maximum index flipped must equal the current step index for the prefix to be aligned.
- 2We can optimize the check for alignment by tracking the maximum index flipped instead of checking the entire prefix.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.