Build a Palindrome


Problem Statement :


You have two strings,  and . Find a string, , such that:

 can be expressed as  where  is a non-empty substring of  and  is a non-empty substring of .
 is a palindromic string.
The length of  is as long as possible.
For each of the  pairs of strings ( and ) received as input, find and print string  on a new line. If you're able to form more than one valid string , print whichever one comes first alphabetically. If there is no valid answer, print  instead.

Input Format

The first line contains a single integer, , denoting the number of queries. The subsequent lines describe each query over two lines:

The first line contains a single string denoting a.
The second line contains a single string denoting  b.

Output Format

For each pair of strings ( ai and bi ), find some si satisfying the conditions above and print it on a new line. If there is no such string, print  - 1  instead.



Solution :



title-img


                            Solution in C :

In    C++  :






#include <bits/stdc++.h>
using namespace std;

inline void wssert(bool b) { if(!b) exit(0); }

const string BAD = "-1";

const int MAXN = 2e5;
const int MAXM = 2e5;
const int MAXL = MAXN * 2 + MAXM * 2 + 20;
int N;
char A[MAXN];
int M;
char B[MAXM];
int L;
char V[MAXL];
int S;

int P[MAXL]; // length of palindrome - 1 / 2
int C[MAXL];

void manacher() {
    int c = 0, r = 0;
    memset(P, 0, sizeof(P));
    for(int i = 0; i < L; ) {
        assert(i - P[i] >= 0);
        assert(i + P[i] < L);
        assert(r == c + P[c]);
        assert(i >= c);
        assert(r >= i + P[i]);
        assert(i == c || r > i + P[i]);
        if(i == c) {
            assert(r == i + P[i]);
            if(i - P[i] - 1 >= 0 && i + P[i] + 1 < L && V[i - P[i] - 1] == V[i + P[i] + 1]) {
                P[i] ++;
                assert(i - P[i] >= 0);
                assert(i + P[i] < L);
            } else {
                i++;
                assert(P[i] == 0);
                assert(i - P[i] >= 0);
                assert(i == L || i + P[i] < L);
            }
       } else {
            assert(i > c);
            assert(r > i + P[i]);
            assert(c - P[c] >= 0);
            assert(c - (i - c) >= 0);
            int v = min(P[c - (i - c)], r - i);
            assert(v >= P[i]);
            if(v > P[i]) {
                P[i] = v;
                assert(i - P[i] >= 0);
                assert(i + P[i] < L);
            } else if (v == r - i) {
                assert(false);
            } else {
                i++;
                assert(P[i] == 0);
                assert(i - P[i] >= 0);
                assert(i == L || i + P[i] < L);
            }
        }
        if(i == L) break;
        if(i + P[i] >= r) {
            c = i;
            r = i + P[i];
        }
        assert(i - P[i] >= 0);
        assert(i + P[i] < L);
    }
}

#define REP(i, n) for(int i = 0; i < int(n); i++)
int gap;
int sa[MAXL], pos[MAXL], tmp[MAXL], lcp[MAXL];

bool sufCmp(int i, int j)
{
    if (pos[i] != pos[j])
        return pos[i] < pos[j];
    i += gap;
    j += gap;
    return (i < L && j < L) ? pos[i] < pos[j] : i > j;
}

void buildSA()
{
    REP(i, L) sa[i] = i, pos[i] = V[i];
    for (gap = 1;; gap *= 2)
    {
        sort(sa, sa + L, sufCmp);
        REP(i, L - 1) tmp[i + 1] = tmp[i] + sufCmp(sa[i], sa[i + 1]);
        REP(i, L) pos[sa[i]] = tmp[i];
        if (tmp[L - 1] == L - 1) break;
    }
}

void buildLCP()
{
    for (int i = 0, k = 0; i < L; ++i) if (pos[i] != L - 1)
    {
        for (int j = sa[pos[i] + 1]; V[i + k] == V[j + k];)
            ++k;
        lcp[pos[i]] = k;
        if (k)--k;
    }
}

string process(int l, int c) {
    string res;
    for(int i = l; i < c; i++) {
        if(V[i] != 124) res += V[i];
    }
    for(int i = c; i >= l; i--) {
        if(V[i] != 124) res += V[i];
    }
    return res;
}

string go() {
    manacher();
    for(int i = 0; i < L; i++) {
        assert(!(i - P[i] - 1 >= 0 && i + P[i] + 1 < L && V[i - P[i] - 1] == V[i + P[i] + 1]));
        //for(int j = 0; j <= P[i]; j++) assert(V[i - j] == V[i + j]);
    }
    memset(C, 0, sizeof(C));
    for(int i = 0; i < L; i++) {
        C[i - P[i]] = max(C[i - P[i]], i);
    }
    for(int i = 1; i < L; i++) {
        C[i] = max(C[i], C[i - 1]);
    }
    buildSA();
    buildLCP();
    for(int i = 0; i < L; i++) {
        //cerr << (V + sa[i]) << '\n';
    }
    for(int i = 0; i + 1 < L; i++) {
        //for(int j = 0; j < lcp[i]; j++) assert(V[sa[i] + j] == V[sa[i + 1] + j]);
        assert(V[sa[i] + lcp[i]] < V[sa[i + 1] + lcp[i]]);
    }
    assert(V[sa[N + M]] == 123);
    int p[2] = {-1, -1};
    int l[2] = {0, 0};
    pair<int, int> res (0, 0);
    for(int i = 0; i < N + M; i++) {
        assert(V[sa[i]] < 123);
        bool d = (sa[i] >= S);
        p[d] = sa[i];
        l[d] = L;
        if(p[!d] != -1) {
            int match = l[!d];
            assert(match % 2 == 0);
            //cerr << p[!d] << ' ' << p[d] << ' ' << match << '\n';
            if(match) res = max(res, make_pair(C[sa[i] + match - 1] - sa[i], -i));
        }
        if(i + 1 < L) l[0] = min(lcp[i], l[0]), l[1] = min(lcp[i], l[1]);
    }
    p[0] = p[1] = -1;
    l[0] = l[1] = -1;
    for(int i = N + M - 1; i >= 0; i--) {
        bool d = (sa[i] >= S);
        p[d] = sa[i];
        l[d] = L;
        if(p[!d] != -1) {
            int match = l[!d];
            assert(match % 2 == 0);
            if(match) res = max(res, make_pair(C[sa[i] + match - 1] - sa[i], -i));
        }
        if(i > 0) l[0] = min(lcp[i - 1], l[0]), l[1] = min(lcp[i-1], l[1]);
    }
    //cerr << res << '\n';
    if(res.first == 0) return BAD;
    return process(sa[-res.second], sa[-res.second] + res.first);
}

int main() {
    int Q; cin >> Q;
    while(Q --> 0) {
        cin >> A >> B;
        N = strlen(A), M = strlen(B);
        L = 0;
        for(int i = 0; i < N; i++) {
            V[L++] = A[i];
            V[L++] = 124;
        }
        V[L++] = 123;
        V[L++] = 125;
        S = L;
        for(int i = M - 1; i >= 0; i--) {
            V[L++] = B[i];
            V[L++] = 124;
        }
        V[L] = 0;
        assert(L == 2 * N + 2 * M + 2);
        cout << go() << '\n';
    }
    return 0;
}









In   Java  :








import java.util.*;

public class PalindromeBuilder {
public static class State {
int length;
int link;
int[] next = new int[128];
int endpos;
final List<Integer> ilink;

public State()
{
Arrays.fill(next, -1);
ilink = new ArrayList<>();
}
}

public static State[] buildSuffixAutomaton(String s) {
int n = s.length();
State[] st = new State[Math.max(2, 2 * n - 1)];
st[0] = new State();
st[0].link = -1;
st[0].endpos = -1;
int last = 0;
int size = 1;
for (char c : s.toCharArray()) {
int cur = size++;
st[cur] = new State();
st[cur].length = st[last].length + 1;
st[cur].endpos = st[last].length;

int p = go(st, last, -1, c, cur);
if (p == -1) {
st[cur].link = 0;
} else {
int q = st[p].next[c];
if (st[p].length + 1 == st[q].length)
st[cur].link = q;
else {
int clone = size++;
st[clone] = new State();
st[clone].length = st[p].length + 1;
st[clone].next = st[q].next.clone();
st[clone].link = st[q].link;
go(st, p, q, c, clone);
st[q].link = clone;
st[cur].link = clone;
st[clone].endpos = -1;
}
}
last = cur;
}
for (int i = 1; i < size; i++) {
st[st[i].link].ilink.add(i);
}
return Arrays.copyOf(st, size);
}

private static int go(State[] st, 
int p, int q, char c, int ns) {
while (p != -1 && st[p].next[c] == q) {
st[p].next[c] = ns;
p = st[p].link;
}
return p;
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; ++i) {
String a = sc.next();
String b = sc.next();
System.out.println(solve(a, b));
}
}

static String candidate(String a, String b) {
State[] as = buildSuffixAutomaton(a);
int[] l = buildPalindromeLookup(b);

int len = 0;

int bestHalf = 0;
int bestMid = 0;
int bestTotal = 0;
int start = -1;
for (int i = 0, aPos = 0; i < b.length(); ++i) {
char c = b.charAt(i);
if (as[aPos].next[c] == -1) {
while (aPos != -1 && as[aPos].next[c] == -1) {
aPos = as[aPos].link;
}
if (aPos == -1) {
aPos = 0;
len = 0;
continue;
}
len = as[aPos].length;
}
++len;
aPos = as[aPos].next[c];

int nStart = i - len + 1;
int nMid = 0;
if (i + 1 < b.length()) {
nMid = l[i + 1];
}
int nTotal = 2*len + nMid;

if (bestTotal < nTotal || (
bestTotal == nTotal && gt(
b, start, nStart, len + nMid))) {
bestHalf = len;
bestMid = nMid;
bestTotal = nTotal;
start = nStart;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bestHalf + bestMid; ++i) {
sb.append(b.charAt(start + i));
}
for (int i = bestHalf - 1; i >= 0; --i) {
sb.append(sb.charAt(i));
}
return sb.toString();
}

static String solve(String a, String b) {
String rb = rev(b);
String res = candidate(a, rb);
String c1 = candidate(rb, a);
if (c1.length() > res.length() || (
c1.length() == res.length() && c1.compareTo(res) < 0)) {
res = c1;
}
if (res.length() == 0) {
res = "-1";
}
return res;
}

static String rev(String s) {
StringBuilder sb = new StringBuilder();
for (int i = s.length() - 1; i >= 0; --i) {
sb.append(s.charAt(i));
}
return sb.toString();
}

static boolean gt(String s, 
int start, int nStart, int size) {
int cmp = 0;
for (int i = 0; i < size; ++i) {
cmp = Character.compare(
    s.charAt(start + i), s.charAt(nStart + i));
if (cmp != 0) {
break;
}
}
return cmp > 0;
}

static int[] buildPalindromeLookup(String s) {
char[] s2 = addBoundaries(s.toCharArray());
int[] p = new int[s2.length];
int c = 0, r = 0;
int m = 0, n = 0;
for (int i = 1; i < s2.length; i++) {
if (i > r) {
p[i] = 0;
m = i - 1;
n = i + 1;
} else {
int i2 = c * 2 - i;
if (p[i2] < (r-i)) {
p[i] = p[i2];
m = -1;
} else {
p[i] = r - i;
n = r + 1;
m = i * 2 - n;
}
}
while (m >= 0 && n < s2.length && s2[m] == s2[n]) {
p[i]++;
m--;
n++;
}
if ((i + p[i]) > r) {
c = i;
r = i + p[i];
}
}
int[] res = new int[s.length()];
for (int i = 1; i < s2.length - 1; i++) {
int idx = (i - p[i])/2;
res[idx] = Math.max(res[idx], p[i]);
}
return res;
}

private static char[] addBoundaries(char[] cs) {
if (cs == null || cs.length == 0)
return "||".toCharArray();

char[] cs2 = new char[cs.length * 2 + 1];
for (int i = 0; i < cs2.length - 1; i += 2) {
cs2[i] = '|';
cs2[i + 1] = cs[i / 2];
}
cs2[cs2.length - 1] = '|';
return cs2;
}
}
                        








View More Similar Problems

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →