title: Permutation of an array of strings
body: <p>I am solving this challenge : 
  <a href="https://www.hackerrank.com/challenges/permutations-of-strings/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/permutations-of-strings/problem</a></p>
  
  <p>I am using this algorithm : 
  <a href="https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order</a></p>
  
  <p>Suppose I enter my array of strings as <code>{"a", "b", "c"}</code>, then the output should be :</p>
  
  <pre><code>a b c 
  a c b
  b c a
  c b a
  b a c
  c a b
  </code></pre>
  
  <p>Since there are 3 distinct strings, there are 3! = 6 permutations.</p>
  
  <p>The program is also supposed to handle duplicate cases, so if I enter <code>{"a", "b", "b"}</code>, there will only be 3! / 2! = 3 permutations.</p>
  
  <p>Anyways when my program reaches <code>c b a</code> then it quits. Why? How can I fix that? </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  void swap(char** s1, char** s2) // to swap two strings
  {
      char* temp = *s1;
      *s1 = *s2;
      *s2 = temp;
  }
  int next_permutation(int n, char **s)
  {
      /**
      * Complete this method
      * Return 0 when there is no next permutation and 1 otherwise
      * Modify array s to its next permutation
      */
      int k, i, l;
      k = i = l = 0;
  
      for(i = n - 2; i &gt;= 0; i--) // first step
          if(strcmp(s[i], s[i + 1]) &lt; 0) {
              k = i;
              break;
          }
  
  
      if(i == -1)
          return 0;
  
      for(i = n - 1; i &gt;= k + 1; i--) // second step
          if(strcmp(s[k], s[i]) &lt; 0) {
              l = i;
              break;
          }
  
  
      swap(&amp;s[k], &amp;s[l]); // third step
  
      for(i = k + 1; i &lt; n / 2; i++) // fourth step
          swap(&amp;s[i], &amp;s[n - i - 1]);
  
      return 1;
  }
  
  int main() // locked code
  {
      char **s;
      int n;
      scanf("%d", &amp;n);
      s = calloc(n, sizeof(char*));
      for (int i = 0; i &lt; n; i++)
      {
          s[i] = calloc(11, sizeof(char));
          scanf("%s", s[i]);
      }
      do
      {
          for (int i = 0; i &lt; n; i++)
              printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
      } while (next_permutation(n, s));
      for (int i = 0; i &lt; n; i++)
          free(s[i]);
      free(s);
      return 0;
  }
  </code></pre>