↓Skip to main content
  1. LeetCode/

LeetCode 3750: Minimum Number of Flips to Reverse Binary String

·2 mins· ·
LeetCode Easy Two-Pointers Bit-Manipulation String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2025-11-22

  • Submissions: Accepted (first try)

Approach
#

Write n as a binary string s without leading zeros and turn it into its own reverse, one bit flip at a time.

Position i must become s[len - 1 - i], and needs one flip when they differ, so the answer is the number of positions where s and its reverse differ.

From a converging-pointer view: for each pair i and len - 1 - i, if the two characters differ, both must flip, so every mismatched pair contributes 2.

My Solution
#

class Solution:
    def minimumFlips(self, n: int) -> int:
        s = bin(n)[2:]
        return sum(a != b for a, b in zip(s, reversed(s)))

My original built the reversed string first and compared position by position in a loop, which is the same logic.

Complexity
#

Time O(log n), space O(log n).

Mistakes to Avoid
#

  • Forgetting to strip the leading 0b from bin(n).
  • Reversing into “another number” and comparing values: the comparison is bit by bit.

Interview Explanation
#

I convert n to a binary string and compare it with its reverse position by position; the number of mismatches is the number of flips, since each mismatched bit needs exactly one flip. Time is proportional to the number of bits, O(log n).

Related

LeetCode 1768: Merge Strings Alternately
·2 mins
LeetCode Easy Two-Pointers String
LeetCode 1768 note: take characters in turn with one index, then append whatever remains of the longer string
LeetCode 2000: Reverse Prefix of Word
·1 min
LeetCode Easy Two-Pointers String Stack
LeetCode 2000 note: find the first index i of ch, reverse word[:i + 1] and append the rest; return the word unchanged if ch is absent
LeetCode 942: DI String Match
·1 min
LeetCode Easy Array Two-Pointers String Greedy
LeetCode 942 note: two pointers hold the smallest and largest unused values; place the smallest on I and the largest on D
LeetCode 557: Reverse Words in a String III
·1 min
LeetCode Easy Two-Pointers String
LeetCode 557 note: split on spaces, reverse each word, and join with spaces
LeetCode 345: Reverse Vowels of a String
·1 min
LeetCode Easy Two-Pointers String
LeetCode 345 note: the same two pointers as LC 917, with the condition switched to “is a vowel” (both cases)
LeetCode 917: Reverse Only Letters
·2 mins
LeetCode Easy Two-Pointers String
LeetCode 917 note: two pointers each skip non-letters and swap when both point at letters; convert the string to a list first