Construct binary palindrome by repeated appending and trimming
Last Updated : 14 Sep, 2022
Given n and k, Construct a palindrome of size n using a binary number of size k repeating itself to wrap into the palindrome. The palindrome must always begin with 1 and contains maximum number of zeros.
Examples :
Input : n = 5, k = 3 Output : 11011 Explanation : the 3 sized substring is 110 combined twice and trimming the extra 0 in the end to give 11011. Input : n = 2, k = 8 Output : 11 Explanation : the 8 sized substring is 11...... wrapped to two places to give 11.
The naive approach would be to try every palindrome of size k starting with 1 such that a palindrome of size n is formed. This approach has an exponential complexity.
A better way to do this is to initialize the k sized binary number with the index and connect the palindrome in the way it should be. Like last character of palindrome should match to first, find which indexes will be present at those locations and link them. Set every character linked with 0th index to 1 and the string is ready. This approach will have a linear complexity.
In this approach, first lay the index of the k sized binary to hold into an array, for example if n = 7, k = 3 arr becomes [0, 1, 2, 0, 1, 2, 0]. Following that in the connect chars graph, connect the indices of the k sized binary which should be same by going through the property of palindrome which is kth and (n - k - 1)th variable should be same, such that 0 is linked to 1(and vice versa), 1 is linked to 2(and vice versa) and so on. After that, check what is linked with 0 in connect chars array and make all of the associated indices one (because the first number should be non-zero) by using dfs approach. In the dfs, pass 0, the final answer string and the graph.
Begin by making the parent 1 and checking if its children are zero, if they are make them and their children 1. This makes only the required indices of the k sized string one, others are left zero. Finally, the answer contains the 0 to k - 1 indexes and corresponding to arr the digits are printed.
Implementation:
C++ // CPP code to form binary palindrome #include <iostream> #include <vector> using namespace std; // function to apply DFS void dfs(int parent, int ans[], vector<int> connectchars[]) { // set the parent marked ans[parent] = 1; // if the node has not been visited set it and // its children marked for (int i = 0; i < connectchars[parent].size(); i++) { if (!ans[connectchars[parent][i]]) dfs(connectchars[parent][i], ans, connectchars); } } void printBinaryPalindrome(int n, int k) { int arr[n], ans[n] = { 0 }; // link which digits must be equal vector<int> connectchars[k]; for (int i = 0; i < n; i++) arr[i] = i % k; // connect the two indices for (int i = 0; i < n / 2; i++) { connectchars[arr[i]].push_back(arr[n - i - 1]); connectchars[arr[n - i - 1]].push_back(arr[i]); } // set everything connected to // first character as 1 dfs(0, ans, connectchars); for (int i = 0; i < n; i++) cout << ans[arr[i]]; } // driver code int main() { int n = 10, k = 4; printBinaryPalindrome(n, k); return 0; }
Java // JAVA code to form binary palindrome import java.util.*; class GFG { // function to apply DFS static void dfs(int parent, int ans[], Vector<Integer> connectchars[]) { // set the parent marked ans[parent] = 1; // if the node has not been visited set it and // its children marked for (int i = 0; i < connectchars[parent].size(); i++) { if (ans[connectchars[parent].get(i)] != 1) dfs(connectchars[parent].get(i), ans, connectchars); } } static void printBinaryPalindrome(int n, int k) { int []arr = new int[n]; int []ans = new int[n]; // link which digits must be equal Vector<Integer> []connectchars = new Vector[k]; for (int i = 0; i < k; i++) connectchars[i] = new Vector<Integer>(); for (int i = 0; i < n; i++) arr[i] = i % k; // connect the two indices for (int i = 0; i < n / 2; i++) { connectchars[arr[i]].add(arr[n - i - 1]); connectchars[arr[n - i - 1]].add(arr[i]); } // set everything connected to // first character as 1 dfs(0, ans, connectchars); for (int i = 0; i < n; i++) System.out.print(ans[arr[i]]); } // Driver code public static void main(String[] args) { int n = 10, k = 4; printBinaryPalindrome(n, k); } } // This code is contributed by PrinciRaj1992
Python3 # Python3 code to form binary palindrome # function to apply DFS def dfs(parent, ans, connectchars): # set the parent marked ans[parent] = 1 # if the node has not been visited # set it and its children marked for i in range(len(connectchars[parent])): if (not ans[connectchars[parent][i]]): dfs(connectchars[parent][i], ans, connectchars) def printBinaryPalindrome(n, k): arr = [0] * n ans = [0] * n # link which digits must be equal connectchars = [[] for i in range(k)] for i in range(n): arr[i] = i % k # connect the two indices for i in range(int(n / 2)): connectchars[arr[i]].append(arr[n - i - 1]) connectchars[arr[n - i - 1]].append(arr[i]) # set everything connected to # first character as 1 dfs(0, ans, connectchars) for i in range(n): print(ans[arr[i]], end = "") # Driver Code if __name__ == '__main__': n = 10 k = 4 printBinaryPalindrome(n, k) # This code is contributed by PranchalK
C# // C# code to form binary palindrome using System; using System.Collections.Generic; class GFG { // function to apply DFS static void dfs(int parent, int []ans, List<int> []connectchars) { // set the parent marked ans[parent] = 1; // if the node has not been visited set it and // its children marked for (int i = 0; i < connectchars[parent].Count; i++) { if (ans[connectchars[parent][i]] != 1) dfs(connectchars[parent][i], ans, connectchars); } } static void printBinaryPalindrome(int n, int k) { int []arr = new int[n]; int []ans = new int[n]; // link which digits must be equal List<int> []connectchars = new List<int>[k]; for (int i = 0; i < k; i++) connectchars[i] = new List<int>(); for (int i = 0; i < n; i++) arr[i] = i % k; // connect the two indices for (int i = 0; i < n / 2; i++) { connectchars[arr[i]].Add(arr[n - i - 1]); connectchars[arr[n - i - 1]].Add(arr[i]); } // set everything connected to // first character as 1 dfs(0, ans, connectchars); for (int i = 0; i < n; i++) Console.Write(ans[arr[i]]); } // Driver code public static void Main(String[] args) { int n = 10, k = 4; printBinaryPalindrome(n, k); } } // This code is contributed by PrinciRaj1992
JavaScript <script> // Javascript code to form binary palindrome // function to apply DFS function dfs(parent, ans, connectchars) { // set the parent marked ans[parent] = 1; // if the node has not been visited set it and // its children marked for (let i = 0; i < connectchars[parent].length; i++) { if (!ans[connectchars[parent][i]]) dfs(connectchars[parent][i], ans, connectchars); } } function printBinaryPalindrome(n, k) { let arr = new Array(n), ans = new Array(n).fill(0); // link which digits must be equal let connectchars = new Array(k).fill(0).map(() => new Array(k).fill(0)); for (let i = 0; i < n; i++) arr[i] = i % k; // connect the two indices for (let i = 0; i < n / 2; i++) { connectchars[arr[i]].push(arr[n - i - 1]); connectchars[arr[n - i - 1]].push(arr[i]); } // set everything connected to // first character as 1 dfs(0, ans, connectchars); for (let i = 0; i < n; i++) document.write(ans[arr[i]]); } // driver code let n = 10, k = 4; printBinaryPalindrome(n, k); // This code is contributed by gfgking. </script>
Time Complexity: O(n)
Similar Reads
Make Palindrome binary string with exactly a 0s and b 1s by replacing wild card ?
Given a string S of N characters consisting of '?', '0', and '1' and two integers a and b, the task is to find a palindromic binary string with exactly a 0s and b 1s by replacing the '?' with either '0' or '1'. Examples: Input: S = "10?????1", a = 4, b = 4Output: 10100101Explanation: The output stri
12 min read
Find if string is K-Palindrome or not | Set 2
Given a string, find out if the string is K-Palindrome or not. A K-palindrome string transforms into a palindrome on removing at most k characters from it.Examples: Input : String - abcdecba, k = 1 Output : Yes String can become palindrome by removing 1 character i.e. either d or e Input : String -
9 min read
Find if string is K-Palindrome or not | Set 1
Given a string S, find out if the string is K-Palindrome or not. A K-palindrome string transforms into a palindrome on removing at most K characters from it.Examples : Input: S = "abcdecba", k = 1Output: YesExplanation: String can become palindrome by removing 1 character i.e. either d or e. Input:
15+ min read
Reverse and Add given number repeatedly to get a Palindrome number
Write a program that takes number and gives the resulting palindrome (if one exists). If it took more than 1, 000 iterations (additions) or yield a palindrome that is greater than 4, 294, 967, 295, assume that no palindrome exist for the given number. Examples: Input: N = 195 Output: 9339 Input: N =
6 min read
Longest Palindrome in a String formed by concatenating its prefix and suffix
Given a string str consisting of lowercase English letters, the task is to find the longest palindromic string T which satisfies the following condition: T = p + m + s where p and s are the prefix and the suffix of the given string str respectively and the string m is either the prefix or suffix of
13 min read
Check given string is oddly palindrome or not | Set 2
Given string str, the task is to check if characters at the odd indexes of str form a palindrome string or not. If not then print "No" else print "Yes". Examples: Input: str = "osafdfgsg", N = 9 Output: Yes Explanation: Odd indexed characters are = { s, f, f, s } so it will make palindromic string,
12 min read
Count Palindromic Substrings in a Binary String
Given a binary string S i.e. which consists only of 0's and 1's. Calculate the number of substrings of S which are palindromes. String S contains at most two 1's. Examples: Input: S = "011"Output: 4Explanation: "0", "1", "1" and "11" are the palindromic substrings. Input: S = "0" Output: 1Explanatio
7 min read
Count of Palindromic substrings in an Index range
Given a string str of small alphabetic characters other than this we will be given many substrings of this string in form of index tuples. We need to find out the count of the palindromic substrings in given substring range. Examples: Input : String str = "xyaabax" Range1 = (3, 5) Range2 = (2, 3) Ou
11 min read
Longest palindrome formed by concatenating and reordering strings of equal length
Given an array arr[] consisting of N strings of equal length M, the task is to create the longest palindrome by concatenating the strings. Reordering and discarding some strings from the given set of strings can also be done.Examples: Input: N = 3, arr[] = { "tab", "one", "bat" }, M = 3 Output: tabb
9 min read
Check if a given string is a rotation of a palindrome
Given a string, check if it is a rotation of a palindrome. For example your function should return true for "aab" as it is a rotation of "aba". Examples: Input: str = "aaaad" Output: 1 // "aaaad" is a rotation of a palindrome "aadaa" Input: str = "abcd" Output: 0 // "abcd" is not a rotation of any p
15+ min read