Find number of Distinct Permutations of a String

Objective – Given a string, find the number of distinct permutations or anagrams of that string.

Example:

String x = "abc"
Output: 6 (abc, acb, bac, bca, cab, cba)

String x = "aab"
Output: 3 (aab, aba, baa)

Approach:

  • Number of ways to arrange n distinct items are = n!.
  • If we have duplicate items, say one item repeated m1 times, then we need to divide n! by m1!. Since these items can be arranged in m1! ways but that will not produce any different results.
  • For example let’s say we have 6 items {a, b, a, c, d, c}, we have ‘a’ which is occurring twice. So in one of the permutation – ‘aabccd’ . if we replace ‘a’ at 0th index and ‘a’ at 1st index, it will not produce any different result. ‘aa’ can be arranged in !2 ways. Same with ‘c’ So our final result will be 6!/(2!*2!).

Let’s drive a generic formula –

Number of permutations Formula

 

Implementation:

  • Count all the characters in the given string, say its N.
  • Calculate N!, this might be our final result if none of the characters are repeated.
  • Count the occurrences of all the characters, store it. We are using Hash Map in our implementation below.
  • Find the factorial of all the counts and divide the result by these factorials. (Non repeated characters will have count 1 and 1! = 1 so dividing by 1 will not affect our final result.)

Code:



Output:

Number of distinct permutations of String: 'abc' are: 6
Number of distinct permutations of String: 'aabc' are: 12
Number of distinct permutations of String: 'aabccd' are: 180

Read Next Article : Print All The Permutations Of a String

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

  • lipsa patel

    For 2nd Example
    Output: 2 (aab, aba, baa)

    it should be

    Output: 3

    • tutorialhorizon

      Thanks Lipsa. We have corrected it.

%d bloggers like this: