703472. Construct binary palindrome by repeated appending and trimming

Medium

Construct Binary Palindrome by Repeated Appending and Trimming

Summary

Construct a binary palindrome by repeatedly appending and trimming a given binary number. A binary palindrome is a binary string that reads the same forwards and backwards. The problem requires us to develop an algorithm to construct this binary palindrome.

Detailed Explanation

The approach to solve this problem involves a combination of DFS (Depth-First Search) and manipulation of binary strings. We start by creating a binary string from the given number. Then, we use DFS to append and trim the binary string until it becomes a palindrome.

Here's a step-by-step breakdown of the solution:

  1. Convert the given binary number into a binary string.
  2. Initialize an empty binary string palindrome to store the constructed palindrome.
  3. Start a DFS from the first character of the binary string, moving towards the end.
  4. For each character in the binary string, append it to palindrome if it is equal to the corresponding character at the opposite end of the palindrome (i.e., the same position but on the other side). If not, trim the last character from the palindrome and move towards the center.
  5. Continue this process until the DFS reaches the middle of the binary string or the entire string has been processed.
  6. The resulting palindrome is the constructed binary palindrome.

Time Complexity: O(n), where n is the length of the input binary number. Space Complexity: O(1), as we only use a constant amount of space to store the palindrome.

Optimized Solutions

Java

View on GeeksforGeeks
public class BinaryPalindrome {
    public static String constructBinaryPalindrome(int n) {
        StringBuilder palindrome = new StringBuilder();
        String binaryStr = Integer.toBinaryString(n);

        for (int i = 0; i < binaryStr.length(); i++) {
            if (i == 0 || i == binaryStr.length() - 1) {
                palindrome.append(binaryStr.charAt(i));
            } else {
                palindrome.append(binaryStr.charAt(i));
                while (!palindrome.toString().equals(reverseString(palindrome.toString()))) {
                    palindrome.deleteCharAt(palindrome.length() - 1);
                }
            }
        }

        return palindrome.toString();
    }

    private static String reverseString(String s) {
        StringBuilder sb = new StringBuilder(s).reverse();
        return sb.toString();
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.