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

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →

Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →

Heavy Light 2 White Falcon

White Falcon was amazed by what she can do with heavy-light decomposition on trees. As a resut, she wants to improve her expertise on heavy-light decomposition. Her teacher gave her an another assignment which requires path updates. As always, White Falcon needs your help with the assignment. You are given a tree with N nodes and each node's value Vi is initially 0. Let's denote the path fr

View Solution →

Library Query

A giant library has just been inaugurated this week. It can be modeled as a sequence of N consecutive shelves with each shelf having some number of books. Now, being the geek that you are, you thought of the following two queries which can be performed on these shelves. Change the number of books in one of the shelves. Obtain the number of books on the shelf having the kth rank within the ra

View Solution →