HackerRank Morgan and a String Problem Solution Yashwant Parihar, April 30, 2023May 6, 2023 In this bpost, we will solve HackerRank Morgan and a String Problem Solution. 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 = [A, C, A] and Daniel has b = [B, C, F]. 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. 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. 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 Problem Solution Morgan and a String C Solution #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #define MaxLength (100000) char _A[MaxLength+2]; char _B[MaxLength+2]; char _C[2*MaxLength+1]; int main() { int i, tests; char *A, *B, *C; scanf("%d\n", &tests); for (; tests > 0; tests--) { A = &(_A[0]); B = &(_B[0]); C = &(_C[0]); scanf("%s", A); scanf("%s", B); int lenA = strlen(A); int lenB = strlen(B); A[lenA] = B[lenB] = 'z'; A[lenA+1] = B[lenB+1] = '\0'; i = 0; while (*A && *B) { if (*A < *B) { *C++ = *A++; } else if (*A > *B) { *C++ = *B++; } else { int cmp = strcmp(A, B); if (cmp <= 0) { *C++ = *A++; } else { *C++ = *B++; } } } while (*A) { *C++ = *A++; } C--; while (*B) { i++; *C++ = *B++; } C--; *C = '\0'; printf("%s\n", _C); } } Morgan and a String C++ Solution #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <string> #include <algorithm> #include <map> #include <functional> #include <iterator> using namespace std; template <typename FwdIt, typename OutIt> OutIt gen_lexi_min(FwdIt a_beg, FwdIt a_end, FwdIt b_beg, FwdIt b_end, OutIt out) { auto a_it = a_beg, b_it = b_beg; while (a_it != a_end && b_it != b_end) { if (*a_it == *b_it) { auto i_it = a_it, j_it = b_it; auto first = *a_it; // we will apply greed algorithm to process as much equal chars in the // two strings as possible. Everytime a range is written to the output // the corrosponding a and b iterator is updated. while (i_it != a_end && j_it != b_end) { if (*i_it != *j_it) { break; } else if (*i_it > first) { std::copy(a_it, i_it, out); std::copy(b_it, j_it, out); first = *i_it; a_it = i_it; b_it = j_it; } // move the equivilent range to the next chars i_it++; j_it++; } if (i_it == a_end) { *out++ = *b_it++; } else if (j_it == b_end) { *out++ = *a_it++; } else { // find the smaller of the two char, that will determine the // range we need to copy into output if (*i_it < *j_it) { *out++ = *a_it++; } else { *out++ = *b_it++; } } } else if (*a_it < *b_it) *out++ = *a_it++; else *out++ = *b_it++; } // flush out remaining chars std::copy(a_it, a_end, out); std::copy(b_it, b_end, out); return out; } int main() { int cases; std::cin >> cases; while (cases--) { // Jack and daniel's string std::string jack, daniel, morgan; std::cin >> jack >> daniel; // find morgan's lexigraphically min string gen_lexi_min(jack.begin(), jack.end(), daniel.begin(), daniel.end(), std::ostream_iterator<char>(std::cout)); std::cout << std::endl; } return 0; } Morgan and a String C Sharp Solution using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace Solution { class Program { static void Main(string[] args) { //using (var provider = new ImputProvider("out.txt")) //{ // var str1 = provider.GetLine(); // var str2 = provider.GetLine(); // for (int i = 0; i < str1.Length; i++) // { // if (str1[i] != str2[i]) // break; // } //} //Stopwatch stopwatch = Stopwatch.StartNew(); using (var provider = new ImputProvider("test.txt")) { new Solution(provider); } //stopwatch.Stop(); //Console.WriteLine(stopwatch.Elapsed); Console.ReadKey(); } public class Solution { string s1, s2; //StreamWriter stream; public Solution(IImputProvider provider) { //stream = new StreamWriter("out.txt"); int T = provider.GetNextInt32(); for (int i = 0; i < T; i++) { s1 = provider.GetLine(); s2 = provider.GetLine(); string result = Solve(); //stream.WriteLine(result); Console.WriteLine(result); } //stream.Flush(); //stream.Dispose(); } private string Solve() { int i = 0; int j = 0; var builder = new StringBuilder(); while (i < s1.Length && j < s2.Length) { if (s1[i] == s2[j]) { StringBuilder temp = new StringBuilder(); temp.Append(s1[i]); int tempi = i + 1; int tempj = j + 1; bool append = true; while (tempi < s1.Length && tempj < s2.Length && s1[tempi] <= s1[i] && s2[tempj] <= s2[j] && s1[tempi] == s2[tempj]) { if (s1[tempi] != s1[i]) append = false; if (append) temp.Append(s1[tempi]); tempi++; tempj++; } if (tempi < s1.Length && tempj < s2.Length) { if (s1[tempi] < s2[tempj]) { i += temp.Length; } else { j += temp.Length; } } else if (tempi < s1.Length) { i += temp.Length; } else if (tempj < s2.Length) { j += temp.Length; } else { i += temp.Length; } builder.Append(temp.ToString()); } else if (s1[i] < s2[j]) { builder.Append(s1[i]); i++; } else { builder.Append(s2[j]); j++; } } while (i < s1.Length) { builder.Append(s1[i]); i++; } while (j < s2.Length) { builder.Append(s2[j]); j++; } return builder.ToString(); } } public interface IImputProvider { bool IsEmpty(); string GetLine(); int GetNextInt32(); long GetNextInt64(); double GetNextDouble(); decimal GetNextDecimal(); T[] GetArray<T>(Func<string, T> parser); } public class ImputProvider : IImputProvider, IDisposable { private StreamReader reader; public ImputProvider() { } public ImputProvider(string path) { if (File.Exists(path)) reader = new StreamReader(path); } public bool IsEmpty() { if (reader == null) return false; return reader.EndOfStream; } public string GetLine() { if (reader == null) return Console.ReadLine(); return reader.ReadLine(); } public int GetNextInt32() { return int.Parse(GetLine()); } public uint GetNextUInt32() { return uint.Parse(GetLine()); } public long GetNextInt64() { return long.Parse(GetLine()); } public double GetNextDouble() { return double.Parse(GetLine()); } public decimal GetNextDecimal() { return decimal.Parse(GetLine()); } public T[] GetArray<T>(Func<string, T> parser) { string[] elements = GetLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); T[] array = new T[elements.Length]; for (int i = 0; i < elements.Length; i++) { array[i] = parser(elements[i]); } return array; } public void Dispose() { if (reader == null) return; reader.Dispose(); } } } } Morgan and a String Java Solution import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; class Result { public static String morganAndString(String a, String b) { int m = a.length() + b.length(); a += 'z'; b += 'z'; char[] acA = a.toCharArray(); char[] acB = b.toCharArray(); char[] acM = new char[m]; int iA = 0; int iB = 0; for (int i = 0; i < m; i++) acM[i] = Arrays.compare(acA, iA, acA.length, acB, iB, acB.length) < 0 ? acA[iA++] : acB[iB++]; return String.valueOf(acM); } } public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int t = Integer.parseInt(bufferedReader.readLine().trim()); IntStream.range(0, t).forEach(tItr -> { try { String a = bufferedReader.readLine(); String b = bufferedReader.readLine(); String result = Result.morganAndString(a, b); bufferedWriter.write(result); bufferedWriter.newLine(); } catch (IOException ex) { throw new RuntimeException(ex); } }); bufferedReader.close(); bufferedWriter.close(); } } Morgan and a String JavaScript Solution function lex(a){ let i=0, q=''; do{ if(!a[0].length){ q+=a[1]; a[1]=''; } if(!a[1].length){ q+=a[0]; a[0]=''; } if(a[0].length && a[1].length){ if(a[0] == a[1]){ i=0; }else if(a[0]>a[1]){ i = 1; }else{ i = 0; } if(a[0].charAt(0) == a[1].charAt(0)){ let x= a[0], y = a[1], l = Math.max(x.length, y.length);; x=x.padEnd(l, 'Z'); y=y.padEnd(l, 'Z'); if(x>y){ i = 1; }else{ i = 0; } } q += a[i].charAt(0); a[i] = a[i].substring(1); } } while(a[0].length || a[1].length); console.log(q); } function processData(input) { input = input.split("\n"); let n = input.shift(), c = n; while(n--){ lex(input.splice(0, 2)); } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); if (!String.prototype.padEnd) { String.prototype.padEnd = function padEnd(targetLength,padString) { targetLength = targetLength>>0; //floor if number or convert non-number to 0; padString = String((typeof padString !== 'undefined' ? padString : ' ')); if (this.length > targetLength) { return String(this); } else { targetLength = targetLength-this.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed } return String(this) + padString.slice(0,targetLength); } }; } Morgan and a String Python Solution for test in range(int(input())): a, b = (input() + '~' for line in range(2)) i = j = 0 while not a[i] == b[j] == '~': if a[i:] < b[j:]: print(end=a[i]) i += 1 else: print(end=b[j]) j += 1 print() Other Solutions HackerRank Count Strings Problem Solution HackerRank String Function Calculation Solution c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython