Back to Freecodecamp

Challenge 116: Permutation Count

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f01.md

latest1.4 KB
Original Source

--description--

Given a string, return the number of distinct permutations that can be formed from its characters.

  • A permutation is any reordering of the characters in the string.
  • Do not count duplicate permutations.
  • If the string contains repeated characters, repeated arrangements should only be counted once.
  • The string will contain only letters (A-Z, a-z).

For example, given "abb", return 3 because there's three unique ways to arrange the letters: "abb", "bab", and "bba".

--hints--

countPermutations("abb") should return 3.

js
assert.equal(countPermutations("abb"), 3);

countPermutations("abc") should return 6.

js
assert.equal(countPermutations("abc"), 6);

countPermutations("racecar") should return 630.

js
assert.equal(countPermutations("racecar"), 630);

countPermutations("freecodecamp") should return 39916800.

js
assert.equal(countPermutations("freecodecamp"), 39916800);

--seed--

--seed-contents--

js
function countPermutations(str) {

  return str;
}

--solutions--

js
function countPermutations(str) {
  const freq = {};
  for (const ch of str) {
    freq[ch] = (freq[ch] || 0) + 1;
  }

  function factorial(n) {
    let result = 1;
    for (let i = 2; i <= n; i++) result *= i;
    return result;
  }

  const n = str.length;
  let result = factorial(n);

  for (const ch in freq) {
    result /= factorial(freq[ch]);
  }

  return result;
}