DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on • Edited on

All Permutation in String

const permute = function (nums) {
  const result = [];

  const findPermutations = (freeNums, fixedNums = []) => {
    if (freeNums.length === 1) {
        result.push(fixedNums.concat(freeNums));
    } else {
      for (let i = 0; i < freeNums.length; i++) {
        const nextFreeNums = [...freeNums];
        const nextFixedNum = nextFreeNums.splice(i, 1);
        findPermutations(nextFreeNums, fixedNums.concat(nextFixedNum));
      }
    }
  };

  findPermutations(nums);

  return result;
};

console.log(permute("abc"));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)