This post is completed by 1 user

  • 0
Add to List
Medium

305. 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:

  1. The number of ways to arrange n distinct items is = n!.
  2. 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.
  3. 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 permutations - ‘aabccd’ . if we replace ‘a’ at the 0th index and ‘a’ at the 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:

  1. Count all the characters in the given string, say it N.
  2. Calculate N!, this might be our final result if none of the characters are repeated.
  3. Count the occurrences of all the characters, and store it. We are using Hash Map in our implementation below.
  4. 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.)
 

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