From 32f86afd250940132e24d4942f125fe2ca8f54a4 Mon Sep 17 00:00:00 2001 From: Pratyay Banerjee <48355572+Neilblaze@users.noreply.github.com> Date: Fri, 11 Oct 2019 11:51:45 +0530 Subject: [PATCH 1/2] Update Contributors.md --- Contributors.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Contributors.md b/Contributors.md index 9c826ec..bd65f5f 100644 --- a/Contributors.md +++ b/Contributors.md @@ -14,4 +14,4 @@ 12. [Hacker-set](https://github.com/Hacker-set)] 13. [Prateek Sengar]https://github.com/prtksengar3) 14. [ANant Rungta](https://github.com/Anant016) - +15. [Pratyay Banerjee](https://github.com/Neilblaze) From fb6639c75e84ea346221dd625f55fac96a90ca49 Mon Sep 17 00:00:00 2001 From: Pratyay Banerjee <48355572+Neilblaze@users.noreply.github.com> Date: Fri, 11 Oct 2019 11:57:09 +0530 Subject: [PATCH 2/2] Create Next_permutation.cpp --- Next_permutation.cpp | 54 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Next_permutation.cpp diff --git a/Next_permutation.cpp b/Next_permutation.cpp new file mode 100644 index 0000000..959da04 --- /dev/null +++ b/Next_permutation.cpp @@ -0,0 +1,54 @@ +/** + * Implement next permutation algorithm. i.e + * Given a word w, rearrange the letters of w to construct another word s in such a way that + * s is lexicographically greater than w. + * In case of multiple possible answers, find the lexicographically smallest one. + * Example: + * ab --> ba + * bb --> bb + * hefg --> hegf + * dhck --> dhkc + * dkhc --> hcdk + */ + +#include + +std::string +next_permutation( std::string str) +{ + int len = str.length(); + int i = len -1; + // We will iterate string from end, and once we have encountered a pair of letters + // such that str[i] < str[i-1] , i-1 would become our pivot + while( i > 0 && str[i] <= str[i-1] ) { + --i; + } + if ( i == 0 ) { + return str; + } + //our pivot right now would be str[i-1] + int j = len - 1; + while( j >= i && str[j] <= str[i-1] ) { + --j; + } + std::swap(str[i-1], str[j]); + j = len - 1; + //reverse the suffix + while( i < j ) { + std::swap(str[i], str[j]); + --j; + ++i; + } + return str; +} + +int main() +{ + std::string str, str_next; + std::cout << "Enter a string : "; + std::cin >> str; + str_next = next_permutation(str); + std::cout << "Next permutation of " << str << " is " + << str_next << std::endl; + return 0; +}