Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda