Minimum Number of Flips to Reverse Binary String Problem
Description
LeetCode Problem 3750.
You are given a positive integer n.
Let s be the binary representation of n without leading zeros.
The reverse of a binary string s is obtained by writing the characters of s in the opposite order.
You may flip any bit in s (change 0 → 1 or 1 → 0). Each flip affects exactly one bit.
Return the minimum number of flips required to make s equal to the reverse of its original form.
Example 1:
Input: n = 7
Output: 0
Explanation:
The binary representation of 7 is "111". Its reverse is also "111", which is the same. Hence, no flips are needed.
Example 2:
Input: n = 10
Output: 4
Explanation:
The binary representation of 10 is "1010". Its reverse is "0101". All four bits must be flipped to make them equal. Thus, the minimum number of flips required is 4.
Constraints:
1 <= n <= 10^9
Solution
Approach: Compare mirrored bits
After the flips, s[i] must equal the original s[m - 1 - i] for every i. So a position needs a flip exactly when it differs from its mirror position in the original string.
Walk two pointers from both ends toward the middle. Each mismatching pair (i, m - 1 - i) makes both of its bits wrong, so it costs two flips. The answer is twice the number of mismatching pairs.
Complexity: time O(log n), space O(log n).
class Solution:
def minimumFlips(self, n: int) -> int:
s = bin(n)[2:]
m = len(s)
return sum(s[i] != s[m - i - 1] for i in range(m // 2)) * 2