Taro Logo

Minimum Operations to Make Binary Palindrome

Medium
Asked by:
Teradata
0 views
Topics:
ArraysBit Manipulation

You are given an integer array nums.

For each element nums[i], you may perform the following operations any number of times (including zero):

  • Increase nums[i] by 1, or
  • Decrease nums[i] by 1.

A number is called a binary palindrome if its binary representation without leading zeros reads the same forward and backward.

Your task is to return an integer array ans, where ans[i] represents the minimum number of operations required to convert nums[i] into a binary palindrome.

Example 1:

Input: nums = [1,2,4]

Output: [0,1,1]

Explanation:

One optimal set of operations:

nums[i] Binary(nums[i]) Nearest
Palindrome
Binary
(Palindrome)
Operations Required ans[i]
1 1 1 1 Already palindrome 0
2 10 3 11 Increase by 1 1
4 100 3 11 Decrease by 1 1

Thus, ans = [0, 1, 1].

Example 2:

Input: nums = [6,7,12]

Output: [1,0,3]

Explanation:

One optimal set of operations:

nums[i] Binary(nums[i]) Nearest
Palindrome
Binary
(Palindrome)
Operations Required ans[i]
6 110 5 101 Decrease by 1 1
7 111 7 111 Already palindrome 0
12 1100 15 1111 Increase by 3 3

Thus, ans = [1, 0, 3].

Constraints:

  • 1 <= nums.length <= 5000
  • ​​​​​​​1 <= nums[i] <= 5000

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the binary string `s` that we can expect?
  2. Are there any constraints or guarantees about the minimum length of the input string, such as whether it can be empty or of length 1?
  3. If multiple different palindromes can be formed with the exact same minimum number of operations, do you have a preference for which one we target, or are we only required to return the minimum operation count?
  4. Is the cost of flipping any character always uniform (i.e., exactly 1 operation per character flip), or could some flips have different weights?
  5. Can the input contain characters other than '0' and '1', or can we strictly assume the string is purely binary?

Brute Force Solution

Approach

To solve this problem using a brute force strategy, we will examine every possible whole number starting from our given starting point and check them one by one. For each number, we will convert it into its binary pattern of zeros and ones and test whether it reads the exact same forwards and backwards. The very first number that satisfies this palindrome condition will be the winner, and we can then count how many steps away it is from our original starting point.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the exact starting number you are given.
  2. Convert this number into its binary format made of zeros and ones.
  3. Check if this binary pattern reads the same forwards and backwards like a palindrome.
  4. If it is already a palindrome, stop right there and report zero operations needed.
  5. If it is not a palindrome, move to the very next whole number.
  6. Convert this new number into its binary format and check if it is a palindrome.
  7. Repeat this checking process for the next number, and the next, moving upwards one by one.
  8. The moment you successfully find a number whose binary pattern is a palindrome, stop searching.
  9. Count how many steps you had to take away from your original starting number to reach this successful palindrome number.
  10. State that count as your final answer.

Code Implementation

def min_operations_binary_palindrome(starting_number):
    current_number = starting_number
    
    while True:
        binary_string = bin(current_number)[2:]
        
        # We check equality against the reversed string to determine if the current binary pattern is symmetric
        if binary_string == binary_string[::-1]:
            return current_number - starting_number
        
        current_number += 1

Big(O) Analysis

Time Complexity
O(infinity) – The time complexity depends on the unknown distance to the nearest greater integer whose binary representation is a palindrome. For each checked number starting from the input n, the algorithm converts it to a binary string and checks for palindromic symmetry, taking time proportional to the number of bits in that integer. Because there is no upper bound on how far we might need to search upwards to find a binary palindrome, the total operations cannot be expressed as a function of n alone. Consequently, the worst-case runtime is unbounded, as the search could theoretically continue indefinitely depending on the bit patterns of integers.
Space Complexity
O(log M) – To evaluate the binary palindrome condition, the algorithm converts integers into their binary string representation or uses bit manipulation to inspect bits. As we test numbers starting from the initial input up to the nearest valid binary palindrome (let this upper bound be M), the maximum value dictates the length of the binary string, which takes logarithmic space relative to the magnitude of the number. Beyond a few primitive loop and tracking variables, the extra memory required is driven solely by storing the binary representation of the current integer being checked. Therefore, the auxiliary space complexity simplifies to O(log M), where M is the final palindrome number found.

Optimal Solution

Approach

Instead of checking every single possible binary combination, the optimal approach works by examining how the binary number reads forward and backward. It systematically adjusts the bits at symmetric positions from the outside in, ensuring we make the fewest changes needed to achieve a mirror image.

Here's how the algorithm would work step-by-step:

  1. Look at the binary representation of the given number as a sequence of digits from both the far left and the far right at the same time.
  2. Compare the digit on the far left with the digit on the far right to see if they match.
  3. If they do not match, decide which digit needs to change to make them identical while keeping the total number of changes as small as possible.
  4. Move inward toward the center, repeating the comparison for the next pair of symmetric positions.
  5. Keep track of every adjustment made until the entire sequence reads the same forwards and backwards.
  6. Verify that the final adjusted sequence successfully forms a valid palindrome with the minimum total effort.

Code Implementation

def min_operations_binary_palindrome(target_number):
    binary_digits_list = list(bin(target_number)[2:])
    left_pointer = 0
    right_pointer = len(binary_digits_list) - 1
    operation_counter = 0

    # We work inward from both ends to align outer bits first for optimal changes.
    while left_pointer < right_pointer:
        if binary_digits_list[left_pointer] != binary_digits_list[right_pointer]:
            binary_digits_list[right_pointer] = binary_digits_list[left_pointer]
            operation_counter += 1

        left_pointer += 1
        right_pointer -= 1

    # Reconstruct the numeric value to guarantee the final state matches expectations.
    final_palindrome_value = int("".join(binary_digits_list), 2)

    # Verification ensures our modifications successfully achieved the target properties.
    binary_representation = bin(final_palindrome_value)[2:]
    if binary_representation == binary_representation[::-1]:
        return operation_counter

    return operation_counter

Big(O) Analysis

Time Complexity
O(log n) – The input size n represents the given number, and the cost is driven by processing its binary representation bit by bit from the outside in. Since the number of bits in the binary representation of n is proportional to log base 2 of n, we examine symmetric pairs moving from the outer edges toward the center. We perform a constant number of operations for each of the roughly log base 2 of n bit positions, leading to approximately log base 2 of n operations. Simplifying this logarithmic growth rate gives a final Big O time complexity of O(log n).
Space Complexity
O(1) – The algorithm only uses a few primitive variables, such as loop counters and pointers, to track symmetric bit positions from the far left and far right. These variables take up a constant amount of extra memory regardless of the size of the input number. No dynamic data structures, recursion stack frames, or auxiliary arrays are needed during the comparison and adjustment steps. Therefore, the auxiliary space complexity remains strictly constant as the input value grows.

Edge Cases

Empty string or single character string
How to Handle:
Return zero operations immediately because an empty or single character string is already a valid palindrome.
String with even length versus odd length
How to Handle:
The two-pointer comparison naturally stops at the middle, correctly ignoring the center character for odd lengths.
String already a palindrome
How to Handle:
The comparison loop will find matching characters at each symmetric position and correctly return zero operations.
String with all zeros or all ones
How to Handle:
Symmetric elements will always match, resulting in zero operations required.
Maximum length string scaling efficiently
How to Handle:
A linear scan using two pointers runs in O(N) time complexity and O(1) auxiliary space, easily passing within execution limits.
Strings with alternating patterns like 010101
How to Handle:
The algorithm compares corresponding symmetric characters and accumulates the minimum flips needed for each mismatch.