Morgan and a String


Problem Statement :


Jack and Daniel are friends. Both of them like letters, especially uppercase ones.
They are cutting uppercase letters from newspapers, and each one of them has his collection of letters stored in a stack.

One beautiful day, Morgan visited Jack and Daniel. He saw their collections. He wondered what is the lexicographically minimal string made of those two collections. He can take a letter from a collection only when it is on the top of the stack. Morgan wants to use all of the letters in their collections.

Note the choice when there was a tie at CA and CF.

Function Description

Complete the morganAndString function in the editor below.

morganAndString has the following parameter(s):

string a: Jack's letters, top at index 0
string b: Daniel's letters, top at index 0


Returns
- string: the completed string

Input Format

The first line contains the an integer t, the number of test cases.

The next t pairs of lines are as follows:
- The first line contains string a
- The second line contains string b.


Constraints


1  <=   T   <=   5
1   <=   | a |, | b |  <=  10^5
a and b contain upper-case letters only, ascii[A-Z].



Solution :



title-img


                            Solution in C :

In   C++ :







// macros {{{
#include <bits/stdc++.h>

using namespace std;

#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
#define BIT(n) ((1LL) << (long long)(n))
#define FOR(i,c) for (auto i=(c).begin(); i != (c).end(); ++i)
#define REP(i,n) for (int i = 0; i < (int)(n); ++i)
#define REP1(i,a,b) for (int i=(int)(a); i <= (int)(b); ++i)
#define MP make_pair
#define PB push_back

#define Fst first
#define Snd second

#ifdef WIN32
#define LLD "%I64d"
#else
#define LLD "%lld"
#endif

typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef long double ld;

typedef pair<int, int> PII;
typedef vector<int> VI;

#define runtime() ((double)clock() / CLOCKS_PER_SEC)

const double eps = 1e-7;
// }}}

#define MAX 100005

#define BASE 27
#define MOD 1000000007

char sa[MAX];
char sb[MAX];
ll ta[MAX];
ll tb[MAX];

ll pw[MAX];
int n, m;

ll getHash(int l, int r, ll table[])
{
    ll tr = l > 0 ? table[l-1] : 1; 
    return (table[r] - pw[r - l + 1] * tr % MOD + MOD) % MOD;
}

bool isSame(int a, int b, int l, int r)
{
    return getHash(a, b, ta) == getHash(l, r, tb);
}

bool check(int i, int j)
{
    int l = 0, r = min(n - i - 1, m - j - 1);

    int ans = r + 1; 
    while (l <= r)
    {
        int mid = (l + r) / 2;

        if (isSame(i, i+mid, j, j+mid))
            l = mid + 1;
        else
            r = mid - 1, ans = mid;
    }
    if (not sa[i + ans]) return false;
    if (not sb[j + ans]) return true;
    return sa[i + ans] <= sb[j + ans];
}

int main()
{
    int T;
    scanf("%d", &T);

    pw[0] = 1;
    for (int i = 1; i < MAX; ++i)
        pw[i] = pw[i-1] * BASE % MOD;

    while (T--)
    {
        scanf("%s %s", sa, sb);
        n = strlen(sa);
        m = strlen(sb);

        ll hash;
        hash = 1;
        for (int i = 0; sa[i]; ++i)
        {
            hash = (hash * BASE + sa[i] - 'A') % MOD;
            ta[i] = hash;
        }
        hash = 1;
        for (int i = 0; sb[i]; ++i)
        {
            hash = (hash * BASE + sb[i] - 'A') % MOD;
            tb[i] = hash;
        }

        string ans;
        int i = 0, j = 0;
        while (sa[i] and sb[j])
        {
            if (check(i, j)) // i <= j
                ans.push_back(sa[i++]);
            else
                ans.push_back(sb[j++]);
        }
        while (sa[i])
            ans.push_back(sa[i++]);
        while (sb[j])
            ans.push_back(sb[j++]);

        printf("%s\n", ans.c_str());
    }
}










In   Java  :






import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
	private static final int MAXSIZE = 200100;
	private static final int ALPHABET = 128;
	
    public static void main(String[] args) {
      
    	Scanner in = new Scanner(System.in);
    	int testcase = Integer.parseInt(in.nextLine());
    	for (int i = 0; i < testcase; i++) {
    		String str1 = in.nextLine();
    		String str2 = in.nextLine();
    		System.out.println(solution(str1 + "a", str2 + "b"));
    	}
    }
    private static List<Integer> buildSuffixArray(String str) {
    	int[] p = new int[MAXSIZE];
    	int[] c = new int[MAXSIZE];
    	int[] cnt = new int[MAXSIZE];
    	int[] pn = new int[MAXSIZE];
    	int[] cn = new int[MAXSIZE];
    	Arrays.fill(cnt, 0);
    	int n = str.length();
    	for (int i = 0; i < n; i++) {
    		++cnt[str.charAt(i)];
    	}
    	for (int i = 1; i < ALPHABET; i++) {
    		cnt[i] += cnt[i - 1];
    	}
    	for (int i = 0; i < n; i++) {
    		p[--cnt[str.charAt(i)]] = i;
    	}
    	int count = 1;
    	c[p[0]] = count - 1;
    	for (int i = 1; i < n; i++) {
    		if (str.charAt(p[i]) != str.charAt(p[i - 1])) {
    			++count;
    		}
    		c[p[i]] = count - 1;
    	}
    	for (int h = 0; (1 << h) < n; ++h) {
    		for (int i =0; i < n; i++) {
    			pn[i] = p[i] - (1 << h);
    			if (pn[i] < 0) {
    				pn[i] += n;
    			}
    		}
    		Arrays.fill(cnt, 0);
    		for (int i = 0; i < n; i++) {
    			++cnt[c[i]];
    		}
    		for (int i = 1; i < count; i++) {
    			cnt[i] += cnt[i - 1];
    		}
    		for (int i = n - 1; i >= 0; i--) {
    			p[--cnt[c[pn[i]]]] = pn[i];
    		}
    		count = 1;
    		cn[p[0]] = count - 1;
    		for (int i = 1; i < n; i++) {
    			int pos1 = (p[i] + (1 << h)) % n;
    			int pos2 = (p[i - 1] +  (1 << h)) % n;
    			if (c[p[i]] != c[p[i - 1]] || c[pos1] != c[pos2]) {
    				++count;
    			}
    			cn[p[i]] = count - 1;
    		}
    		for (int i = 0; i < n; i++) {
    			c[i] = cn[i];
    		}
    	}
    	List<Integer> res = new ArrayList<Integer>(n);
    	for (int i = 0; i < n; i++) {
    		res.add(c[i]);
    	}
    	return res;
    }
    
    private static String solution(String str1, String str2) {
    	StringBuilder sb = new StringBuilder(str1).append(str2);
    	List<Integer> suffix = buildSuffixArray(sb.toString());
    	StringBuilder rst = new StringBuilder();
    	int start1 = 0;
    	int start2 = 0;
    	while (start1 < str1.length() - 1 || start2 < str2.length() - 1) {
    		if (start1 >= str1.length() - 1) {
    			rst.append(str2.charAt(start2++));
    			continue;
    		}
    		if (start2 >= str2.length() - 1) {
    			rst.append(str1.charAt(start1++));
    			continue;
    		}
    		if (suffix.get(start1) < suffix.get(str1.length() + start2)) {
    			rst.append(str1.charAt(start1++));
    		} else {
    			rst.append(str2.charAt(start2++));
    		}
    	}
    	return rst.toString();
    }
}









In   C  :








#include <stdio.h>
#include <string.h>

int is_a(const char* a, const char* b) {
    while (*a && *b) {
        if (*a == *b) {
            a++;
            b++;
        } else {
            return *a < *b;
        }
    }
    return *a != 0;
}

void merge(const char* a, const char* b, char* c) {
    int is_a_preferred = is_a(a, b);
    while (*a && *b) {
        if (*a == *b) {
            *c = (is_a_preferred)? *(a++) : *(b++);
        } else {
            *c = (*a < *b)? *(a++) : *(b++);
            is_a_preferred = is_a(a, b);
        }
        ++c;
    }
    while (*a) {
        *c++ = *a++;
    }
    while (*b) {
        *c++ = *b++;
    }
    *c = '\0';
}

int main() {
    int t;
    char a[100001];
    char b[100001];
    char c[200001];
    scanf("%d", &t);
    while (t--) {
        scanf("%s\n%s", a, b);
        merge(a, b, c);
        printf("%s\n", c);
    }
}








In   Python3  :







from collections import deque
from builtins import range
from builtins import input

for _ in range(int(input())):
    a = input() + '['
    b = input() + '['
    string = deque()
    while len(a) > 1 and len(b) > 1:
        if a < b:
            string.append(a[0])
            a = a[1:]
        else:
            string.append(b[0])
            b = b[1:]
    print(''.join(string) + a[:-1] + b[:-1])
                        








View More Similar Problems

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →