#1529
Minimum Suffix Flips
MediumStringGreedyGreedyTwo Pointers
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)
The optimal solution leverages the observation that we only need to count transitions between '0' and '1' in the target string. Each transition indicates a necessary flip operation, allowing us to minimize the number of operations.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a variable to count the number of flips.
- 2Step 2: Iterate through the target string from the first character to the last.
- 3Step 3: Count a flip whenever the current character differs from the previous character.
- 4Step 4: If the first character is '1', increment the flip count by one.
- 5Step 5: Return the total flip count.
solution.py11 lines
1# Full working Python code
2
3def min_flips(target: str) -> int:
4 flips = 0
5 for i in range(len(target)):
6 if i == 0 and target[i] == '1':
7 flips += 1
8 elif i > 0 and target[i] != target[i - 1]:
9 flips += 1
10 return flips
11ℹ
Complexity note: This is efficient because it only requires a single pass through the target string, counting transitions, leading to linear time complexity.
- 1Flipping from the left affects all bits to the right.
- 2Count transitions between '0' and '1' to minimize operations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.