#3750
Minimum Number of Flips to Reverse Binary String
EasyMathTwo PointersStringBit ManipulationTwo PointersString Manipulation
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)
Using two pointers, we can efficiently compare bits from the start and end of the string, counting mismatches.
⚙️
Algorithm
3 steps- 1Step 1: Convert n to its binary string representation.
- 2Step 2: Initialize two pointers, one at the start and one at the end of the string.
- 3Step 3: Move both pointers towards the center, counting mismatches until they meet.
solution.py8 lines
1def minFlips(n):
2 s = bin(n)[2:]
3 left, right, flips = 0, len(s) - 1, 0
4 while left < right:
5 if s[left] != s[right]: flips += 1
6 left += 1
7 right -= 1
8 return flipsℹ
Complexity note: We only traverse the string once with two pointers, leading to O(n) time complexity.
- 1Flipping bits can be visualized as matching pairs.
- 2Two pointers reduce unnecessary comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.