Best way to get all anagrams of a string | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Best way to get all anagrams of a string

Hi I want to find all permutations i.e. anagrams of a string. One and best way is to use algorithm next_permutation ... What's time complexity of same ? I tried to implement other way and I belive it has n*n time complexity. Whats the best way to achieve the anagrams of a string with best time complexity? https://code.sololearn.com/cA48a25A21A1/?ref=app

25th Jun 2021, 5:55 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 Answers
+ 6
Probably backtracking one is faster as you are just making all permutations in O(n!) complexity, while in next_permutation one you need to start from lexicographically smallest permutation and for making every next permutation you need O(n) complexity so its O(n.n!). But it doesn't matter, if n is greater than 10 or 11 both approaches will result in TLE. backtracking one needs to handle duplicates too can be done by not replacing with same character again, so a set (log n) [ or array (1) if only alphabates ] will be needed too.
25th Jun 2021, 7:44 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 5
Permutations themselved are n! if no repeated characters, so atleast n! will be the complexity which gives TLE easily for n>11, 12! is around 5e8. we can't reduce permutations.
25th Jun 2021, 10:52 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 2
permutations algorithms, even well designed, have like O^n time complexity... meaning that it becomes quickly very long to compute as string length grow ^^
25th Jun 2021, 7:46 PM
visph
visph - avatar
+ 1
Yeah it seems algorithm is also not fully optimised as it results in TLE for larger n.... Don't we have any other approach ?
25th Jun 2021, 8:07 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Also my code is backtracking ? If so, I am getting counter as 16 for n as 3... Does this not means it is not just n!
25th Jun 2021, 8:13 PM
Ketan Lalcheta
Ketan Lalcheta - avatar