HackerRank Morgan and a String Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Morgan and a String Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

HackerRank Morgan and a String Solution
HackerRank Morgan and a String Solution

HackerRank Morgan and a String Solution

Task

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.

As an example, assume Jack has collected a = [ACA] and Daniel has b = [BCF]. The example shows the top at index 0 for each stack of letters. Assemble the string as follows:

Jack	Daniel	result
ACA	BCF
CA	BCF	A
CA	CF	AB
A	CF	ABC
A	CF	ABCA
    	F	ABCAC
    		ABCACF

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

Example

s1 = ‘ABCD’
s2 = ‘ABDC’

These strings have two children with maximum length 3, ABC and ABD. They can be formed by eliminating either the D or C from both strings. Return 3.

Function Description

Complete the morganAndString function in the editor below.

morganAndString has the following parameter(s):

  • string a: Jacks 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| <= 105
  • a and b contain upper-case letters only, ascii[AZ].

Sample Input

2
JACK
DANIEL
ABACABA
ABACABA

Sample Output

DAJACKNIEL
AABABACABACABA

Explanation

The first letters to choose from are J and D since they are at the top of the stack. D is chosen and the options now are J and A. A is chosen. Then the two stacks have J and N, so J is chosen. The current string is DA. Continue this way to the end to get the string.

HackerRank Morgan and a String Solution

HackerRank Morgan and a String Solution in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char str1[100001];
char str2[100001];
void printequal(int *i,int len1,int *j,int len2){
    char c=str1[*i],ci,cj;
    int i1,j1,k;
    for(i1=*i,j1=*j;str1[i1]==str2[j1]&&i1<len1&&j1<len2;i1++,j1++){

         if(str1[i1]>c){
            for(;str1[*i]==c;(*i)++)
                printf("%c",str1[*i]);
            return;
        }
        
    }

        if(i1==len1){
            for(;str2[*j]==c;(*j)++)
                printf("%c",str2[*j]);return;
        }
        else if(j1==len2){
                        for(;str1[*i]==c;(*i)++)
                printf("%c",str1[*i]);return;
            
        }
    else if(str1[i1]<c && str1[i1]<str2[j1]){
        for(;*i<i1;(*i)++)
                printf("%c",str1[*i]);return;
    }
    else if(str2[j1]<c && str1[i1]>str2[j1]){
        for(;*j<j1;(*j)++)
                printf("%c",str2[*j]);return;
    }
    else{
            for(;str1[*i]==c;(*i)++)
                printf("%c",str1[*i]);
            return;
    }

    return;
}

int main(){
    int T,i,j,len1,len2;
    scanf("%d",&T);
    while(T--){
        scanf("%s%s",str1,str2);
        len1=strlen(str1);
        len2=strlen(str2);
        i=0;j=0;
        while(i<len1 || j<len2){
            if(i==len1){
                printf("%c",str2[j]);j++;
            }
            else if(j==len2){
                printf("%c",str1[i]);i++;
            }
            else if(str1[i]<str2[j]){
                printf("%c",str1[i]);i++;
            }
            else if(str1[i]>str2[j]){
                printf("%c",str2[j]);j++;
            }
            else{
                printequal(&i,len1,&j,len2);
            
                
            }
        }
        printf("\n");
        
        
    }
    
   
    return 0;
}

HackerRank Morgan and a String Solution in Cpp

#include <bits/stdc++.h>
#include <unistd.h>
#define SZ(x) ((int)(x).size())
#define ALL(x) begin(x),end(x)
#define REP(i,n) for ( int i=0; i<int(n); i++ )
#define REP1(i,a,b) for ( int i=(a); i<=int(b); i++ )
#define FOR(it,c) for ( __typeof((c).begin()) it=(c).begin(); it!=(c).end(); it++ )
#define MP make_pair
#define PB push_back
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
typedef vector<int> VI;

void RI() {}

template<typename... T>
void RI( int& head, T&... tail ) {
    scanf("%d",&head);
    RI(tail...);
}
// }}}

#define MS0(x,n) memset((x),0,(n)*sizeof(*(x)))

struct SA{

    static const int MXN = 200010;

    bool _isS[MXN*2];
    int _str[MXN*2], _sa[MXN*2], _cnt[MXN*2], _idx[MXN], _p[MXN*2], _rp[MXN*2];

    int operator [] (int idx){ return _sa[idx]; }

    void build(const char *str){
        int n = strlen(str) + 1;
        for(int i = 0; i < n; i++) _str[i] = str[i];
        sais(_str, _sa, _p, _rp, _isS, _cnt, _idx, n, 128);
    }

    void build(const int *str, int n, int m){
        memcpy(_str, str, sizeof(int) * n);
        sais(_str, _sa, _p, _rp, _isS, _cnt, _idx, n, m);
    }

    void sais(int *str, int *sa, int *p, int *rp, bool *isS, int *cnt, int *idx, int n, int z){

        bool uniq = true;
        memset(cnt, 0, sizeof(int) * z);
        for(int i = 0; i < n; i++) uniq &= ++cnt[str[i]] < 2;
        for(int i = 1; i < z; i++) cnt[i] += cnt[i - 1];

        if(uniq){
            for(int i = 0; i < n; i++) sa[--cnt[str[i]]] = i;
            return;
        }

        isS[n - 1] = true;
        for(int i = n - 2; i >= 0; i--){
            if(str[i] == str[i + 1]) isS[i] = isS[i + 1];
            else isS[i] = str[i] < str[i + 1];
        }

        int nn = 0;
        memset(sa, -1, sizeof(int) * n);
        memcpy(idx, cnt, sizeof(int) * z);
        for(int i = 1; i < n; i++){
            if(!isS[i]) continue;
            if(!isS[i - 1] || i == n - 1) sa[--idx[str[i]]] = i, p[nn] = i, rp[i] = nn++;
        }

        memcpy(idx + 1, cnt, sizeof(int) * (z - 1));
        for(int i = 0; i < n; i++){
            if(sa[i] > 0 && !isS[sa[i] - 1]) sa[idx[str[sa[i] - 1]]++] = sa[i] - 1;
        }

        memcpy(idx, cnt, sizeof(int) * z);
        for(int i = n - 1; i >= 0; i--){
            if(sa[i] > 0 && isS[sa[i] - 1]) sa[--idx[str[sa[i] - 1]]] = sa[i] - 1;
        }

        int nmxz = -1;
        int *nsa = sa + n;
        int *nstr = str + n;
        for(int i = 0, lst = -1; i < n; i++){

            int cur = sa[i];
            if(cur == 0 || !isS[cur] || isS[cur - 1]) continue;

            bool neq = lst == -1;
            for(int j = 0; !neq; j++){
                if(str[cur + j] != str[lst + j] || isS[cur + j] != isS[lst + j]) neq = true;
                if(j > 0 && (isS[lst + j] && !isS[lst + j - 1])){ neq = !isS[cur + j]; break; }
            }

            lst = cur;
            nstr[rp[cur]] = neq? ++nmxz: nmxz;

        }

        sais(nstr, nsa, p + nn, rp + n, isS + n, cnt + z, idx, nn, ++nmxz);

        memset(sa, -1, sizeof(int) * n);
        memcpy(idx, cnt, sizeof(int) * z);
        for(int i = nn - 1; i >= 0; i--) sa[--idx[str[p[nsa[i]]]]] = p[nsa[i]];
        
        memcpy(idx + 1, cnt, sizeof(int) * (z - 1));
        for(int i = 0; i < n; i++){
            if(sa[i] > 0 && !isS[sa[i] - 1]) sa[idx[str[sa[i] - 1]]++] = sa[i] - 1;
        }

        memcpy(idx, cnt, sizeof(int) * z);
        for(int i = n - 1; i >= 0; i--){
            if(sa[i] > 0 && isS[sa[i] - 1]) sa[--idx[str[sa[i] - 1]]] = sa[i] - 1;
        }

    }

};


#define N 200010
char s1[N],s2[N],s3[N],ans[N];
int rk[N];
int main() {
    int t;
    RI(t);
    while ( t-- ) {
        SA *sa = new SA;
        scanf("%s%s",s1,s2);
        int n1=strlen(s1);
        int n2=strlen(s2);
        memset(s3,0,sizeof(s3));
        strcat(s3,s1);
        strcat(s3,"~");
        strcat(s3,s2);
        strcat(s3,"~");
        sa->build(s3);
        REP(i,n1+n2+3) rk[sa->_sa[i]]=i;
        int i1=0,i2=0,ia=0;
        while ( i1<n1 && i2<n2 ) {
            int j1=i1;
            int j2=n1+1+i2;
            if ( rk[j1]<rk[j2] ) ans[ia++]=s1[i1++];
            else ans[ia++]=s2[i2++];
        }
        while ( i1<n1 ) ans[ia++]=s1[i1++];
        while ( i2<n2 ) ans[ia++]=s2[i2++];
        ans[ia]=0;
        puts(ans);
        delete sa;
    }
    return 0;
}

HackerRank Morgan and a String Solution in Java

import java.io.*;

public class Solution {
	
	private static int[] createSA(String input, int letters, int maxsize){
		
	int[] first = new int[maxsize];
	int[] second = new int[maxsize];
	int[] third = new int[maxsize];
	int[] count = new int[maxsize];
	int[] suffarr = new int[maxsize];
		
	int size = input.length();
	char[] arr = input.toCharArray();
	for (int i = 0; i < size; i++) count[arr[i]]++;
        for (int j = 1; j < letters; j++) count[j] += count[j-1];
        for (int k = 0; k < size; k++) first[--count[arr[k]]] = k;
        int sum = 1;
        suffarr[first[0]] = 0;
        for (int i = 1; i < size; i++) {
            if (arr[first[i]] != arr[first[i-1]]) sum++;
            suffarr[first[i]] = sum - 1;
        }
        for (int m = 0; (1<<m) < size; m++) {
            for (int i = 0; i < size; i++){
                second[i] = first[i] - (1<<m);
                if (second[i] < 0) second[i] += size;
            }
            count = new int[maxsize];
            for (int i = 0; i < size; i++) count[suffarr[i]]++;
            for (int j = 1; j < sum; j++) count[j] += count[j-1];
            for (int k = size-1; k >= 0; k--) first[--count[suffarr[second[k]]]] = second[k];
            sum = 1;
            third[first[0]] = 0;
            for (int i = 1; i < size; i++){
                int pos1 = (first[i] + (1<<m))%size;
                int pos2 = (first[i-1] + (1<<m))%size;
                if (suffarr[first[i]] != suffarr[first[i-1]] || suffarr[pos1] != suffarr[pos2]) sum++;
                third[first[i]] = sum - 1;
            }
            for (int i = 0; i < size; i++) suffarr[i] = third[i];
        }
		return suffarr;
	}
	
	private static void compute(String first, String second){
		
		StringBuilder result = new StringBuilder();
		String process = first.concat("y").concat(second).concat("z");
		int[] suffarr = createSA(process,128,200005);
		int indexf = 0;
		int fsize = first.length();
		int psize = process.length();
		int indexs = fsize+1;
		
		for(int i = 0; i < process.length(); i++){
			if(indexs > psize-1 && indexf > fsize-1) break;
			if(indexs > psize-1){
				result.append(process.substring(indexf, fsize-1));
				break;
			}
			if(indexf > fsize-1){
				result.append(process.substring(indexs, psize-1));
				break;
			}
			if(suffarr[indexf] < suffarr[indexs]){
				result.append(process.charAt(indexf));
				indexf++;
			}
			else{
				result.append(process.charAt(indexs));
				indexs++;
			}
		}
		
		System.out.println(result.toString());
	}

	public static void main(String[] args) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line;
		String first;
		String second;
		int T;
		
		line = br.readLine();
		T = Integer.parseInt(line);
		for(int i = 0; i < T; i++){
		  first = br.readLine();
		  second = br.readLine();
		  compute(first,second);
		}
	}
}

HackerRank Morgan and a String Solution in Python

T = input()
for i in range(T):
    J = raw_input()
    D = raw_input()
    J += "z"
    D += "z"
    j = 0
    d = 0
    S = ""
    while j < len(J) and d < len(D):
        if J[j:] < D[d:]:
            S += J[j]
            j += 1
        else:
            S += D[d]
            d += 1
    S = S[:-1]
    if j < len(J):
        S += J[j:-1]
    if d < len(D):
        S += D[d:-1]
    print S
            

HackerRank Morgan and a String Solution using JavaScript

function processData(input) {
    var testCases = input.split('\n');
    testCases.shift();
    while (testCases.length) {
        var jack = testCases.shift().split(''),
            daniel = testCases.shift().split('');
        var result = [];
        var chosenStack = undefined, jl, dl;
        while (jack.length || daniel.length) {
            if (!chosenStack || chosenStack[0] !== result[result.length - 1]) {
                chosenStack = undefined;
                jl = jack.length;
                dl = daniel.length;
                if (jl && dl) {
                    var jackStart = jack[0];
                    var danielStart = daniel[0];
                    if (jackStart > danielStart) {
                        chosenStack = daniel;
                    } else if (jackStart < danielStart) {
                        chosenStack = jack;
                    } else {
                        for (var i = 1, length = Math.min(jl, dl); i < length; ++i) {
                            var currentJack = jack[i];
                            var currentDaniel = daniel[i];
                            if (currentJack !== currentDaniel) {
                                chosenStack = currentJack < currentDaniel ? jack : daniel;
                                break;
                            }
                        }
                        if (chosenStack === undefined) {
                            chosenStack = jl > dl ? jack : daniel;
                        }
                    }

                } else if (jl) {
                    chosenStack = jack;
                } else {
                    chosenStack = daniel;
                }
            }
            
            result.push(chosenStack.shift());
        }
        console.log(result.join(''));
    }
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

HackerRank Morgan and a String Solution in Scala

object Solution extends App {
    val testCases = scala.io.StdIn.readLine.toInt
    for(y <- 1 to testCases) {
        val jack = scala.io.StdIn.readLine + "["
        val daniel = scala.io.StdIn.readLine + "]"
        val dLen = daniel.length - 1
        val jLen = jack.length - 1
        val output = StringBuilder.newBuilder
        var jCursor = 0
        var dCursor = 0
        var jCurrent = 0
        var dCurrent = 0
        var oLen = 0
        while (oLen < (dLen + jLen)) {
            if (jCursor >= jLen && dCursor >= dLen) {
                oLen += 1
                output.append(daniel(dCurrent))
                dCurrent += 1
                dCursor = dCurrent
                jCursor = jCurrent
            } else if (jack(jCursor) == daniel(dCursor)) {
                jCursor += 1
                dCursor += 1
            } else {
                if (jack(jCursor) < daniel(dCursor)) {
                    if (jCurrent == jCursor)
                        jCursor += 1
                    val ss = jack.substring(jCurrent, jCursor)
                    output.append(ss)
                    jCurrent += ss.length
                    oLen += ss.length
                } else {
                    if (dCurrent == dCursor)
                        dCursor += 1
                    val ss = daniel.substring(dCurrent, dCursor)
                    output.append(ss)
                    dCurrent += ss.length
                    oLen += ss.length
                }
                jCursor = jCurrent
                dCursor = dCurrent
            }
        }
        println(output.toString())
    }
}

HackerRank Morgan and a String Solution in Pascal

{$I-,O+,Q-,R-,S-}

uses
  sysutils;
var
  t: integer;
  a, b: ansistring;

procedure solve(a, b: ansistring);
var
  ans: ansistring;
  n, m, i, j, ii, jj: int64;
  ok: boolean;
begin
  ans := '';

  n := length(a); m := length(b);
  i := 1; j := 1;
  repeat
    ii := i; jj := j;
    while (ii <= n) and (jj <= m) and (a[ii] = b[jj]) do begin
      inc(ii); inc(jj);
    end;

    if ii > n then
      repeat
        ans += b[j];
        inc(j);
      until (j > m) or (b[j] <> b[j-1])
    else if jj > m then
      repeat
        ans += a[i];
        inc(i);
      until (i > n) or (a[i] <> a[i-1])
    else if a[ii] < b[jj] then
      repeat
        ans += a[i];
        inc(i);
      until (i > n) or (a[i] <> a[i-1])
    else
      repeat
        ans += b[j];
        inc(j);
      until (j > m) or (b[j] <>  b[j-1]);

  until (i > n) and (j > m);

  writeln(ans);
end;

begin
  readln(t);
  repeat
    readln(a); readln(b);

    solve(a, b);

    dec(t);
  until t = 0;
end.

Disclaimer: This problem (Morgan and a String) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

Sharing Is Caring