title: Morgan and a String Algorithm
body: <p>I'm trying the problem from the following link:</p>
  
  <p><a href="https://www.hackerrank.com/challenges/morgan-and-a-string/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/morgan-and-a-string/problem</a></p>
  
  <blockquote>
    <p>Jack and Daniel are friends. Both of them like letters, especially
    upper-case ones.  They are cutting upper-case letters from newspapers,
    and each one of them has their collection of letters stored in
    separate stacks.  One beautiful day, Morgan visited Jack and Daniel.
    He saw their collections. Morgan wondered what is the
    lexicographically minimal string, made of that two collections. He can
    take a letter from a collection when it is on the top of the stack. 
    Also, Morgan wants to use all the letters in the boys' collections.</p>
  </blockquote>
  
  <p>My code is as follows:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;math.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main() {
      int flag,choice;
      long n,i,j=0,k=0,x,y;
      char *a,*b;
      a=(char*)malloc(sizeof(char)*100000);
      b=(char*)malloc(sizeof(char)*100000);
      scanf("%ld",&amp;n);
      for(i=0;i&lt;n;i++){
          j=k=0;
          scanf("%s%s",a,b);
          x=strlen(a);
          y=strlen(b);
          while(x&lt;y)a[x++]='Z'+1;
          while(y&lt;x)b[y++]='Z'+1;
          a[x]=b[y]='\0';
          while(j&lt;x &amp;&amp; k&lt;y &amp;&amp; (a[j]!=('Z'+1) &amp;&amp; b[k]!=('Z'+1))){
  
              if(strcmp(a+j,b+k)&lt;0)printf("%c",a[j++]);
              else printf("%c",b[k++]);
  
          }
          while(j&lt;x &amp;&amp; a[j]!=('Z'+1))printf("%c",a[j++]);
          while(k&lt;y &amp;&amp; b[k]!=('Z'+1))printf("%c",b[k++]);
          printf("\n");
      }
  
      return 0;
  }
  </code></pre>
  
  <p>I compare both the strings after popping each character. Also, I've taken care of strings of unequal length by appending the shorter string with a character larger than any other alphabet in ASCII. I don't get the correct solution every time.</p>
  
  <p>The following works:</p>
  
  <p>Input:</p>
  
  <pre><code>1
  c
  ca
  </code></pre>
  
  <p>Expected and correct output:</p>
  
  <p><code>cac</code></p>
  
  <p>The following doesn't:</p>
  
  <p>Input:</p>
  
  <pre><code>1
  zbc
  aaaaz
  </code></pre>
  
  <p>Expected output:</p>
  
  <p><code>aaaazbcz</code></p>
  
  <p>Actual output:</p>
  
  <p><code>aaaazzbc</code></p>
  
  <p>What is it that I'm missing?</p>