Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
Time Complexity of permutation function Should be T((n!)^2)?

Problem : Given an array of nums of distinct integers, return all the possible permutations.

For example, [1,2,3] have the following permutations: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ].

This is my javascript implementation, similar to the standard solution for this problem. I found many places saying this time complexity is to be T(n*n!). But as I understand it should be T((n!)^2). Again I could be wrong !!.

JavaScript Solution

var permute = function(nums) {
    if(nums.length === 0) return [];
    if(nums.length ===1){
        return [[...nums]]; 
    }
    
    let results = [];
    const len = nums.length;
    for(let i=0; i<len; i++){
        // eg: [1,2,3,4]
        const temp = nums[i]; 
        nums[i] = nums[len-1]; 
        nums[len-1] = temp; // [4,2,3,1]
        const n = nums.pop(); // [4,2,3]
        const prems = permute(nums);
        prems.forEach(perm => perm.push(n));
        results = results.concat(prems); 
        nums.push(nums[i]) // [4,2,3,4]
        nums[i] = temp; // [1,2,3,4]
        
    }
    
    return results;
    
 
};

Here is How I got the answer as T((n!)^2)

so for the outer,

1st itteration
  • Each iteration will do a recursive call with n-1 items array
  • Then the results, which will be all permutations with n-1 items will be size (n-1)!
  • So we have to loop through (n-1)! items to append the popped element.
For n itterations
So for the first recursive call, this will happen n times (the outer loop is going from 0 to n)

So, for the first recursive call T-(n*(n-1)!)

Since the recursion tree size is n! the final time complexity should be - T(n!n(n-1)!) = T((n!)^2).

Am I missing something here ??

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I think your answer is like this:

For the outer loop, n iterations and for permutation n! Therefore, the time complexity of this algorithm is factorial time, which I think  Σ((n-i) * T(n-i)) -> O(n*n!) is your answer

i from 0 to n

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda