HackerRank C- Permutations of Strings




Given an array of strings sorted in lexicographical order, print all of its permutations in strict lexicographical order. If two permutations look the same, only print one of them. See the 'note' below for an example.



  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. int next_permutation(int n, char **s){
  5. // Find non-increasing suffix
  6. int i = n-1;
  7. while(i>0 && strcmp(s[i-1],s[i])>=0)
  8. i--; // find key
  9. if (i<=0) return 0;
  10. // Swap key with its successor in suffix
  11. int j = n-1;
  12. while(strcmp(s[i-1],s[j])>=0)
  13. j--; // find rightmost successor to key
  14. char *tmp = s[i-1];
  15. s[i-1] = s[j];
  16. s[j] = tmp;
  17. // Reverse the suffix
  18. j = n-1;
  19. while(i<j) {
  20. tmp = s[i];
  21. s[i] = s[j];
  22. s[j] = tmp;
  23. i++;
  24. j--;
  25. }
  26. return 1;
  27. }
  28. int main()
  29. {
  30. char **s;
  31. int n;
  32. scanf("%d", &n);
  33. s = calloc(n, sizeof(char*));
  34. for (int i = 0; i < n; i++)
  35. {
  36. s[i] = calloc(11, sizeof(char));
  37. scanf("%s", s[i]);
  38. }
  39. do
  40. {
  41. for (int i = 0; i < n; i++)
  42. printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
  43. } while (next_permutation(n, s));
  44. for (int i = 0; i < n; i++)
  45. free(s[i]);
  46. free(s);
  47. return 0;
  48. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube