DEV Community

codingpineapple
codingpineapple

Posted on

1 1

LeetCode 46. Permutations (javascript solution)

Description:

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Solution:

Time Complexity : O(n!)
Space Complexity: O(n)

var permute = function(choices, temp = [], permutations = []) {
    // Base case 
    if(choices.length === 0){
      permutations.push([...temp]);
    } 

    for(let i = 0; i < choices.length; i++){
        // Create new array without current letter
        let newChoices = choices.filter((choice, index) => index !== i)
        // Add current to the temp array which is our current permutation
        temp.push(choices[i])
        permute(newChoices, temp, permutations)
        // Once we have explored options remove the current letter from our current permuataion
        temp.pop()
    }

    return permutations
};
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
qurashieman profile image
Tuba Inam

I found that solution is very popular and helpful: youtu.be/UvSPsz0jTQ4

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay