47

I'm studying time complexity in school and our main focus seems to be on polynomial time O(n^c) algorithms and quasi-linear time O(nlog(n)) algorithms with the occasional exponential time O(c^n) algorithm as an example of run-time perspective. However, dealing with larger time complexities was never covered.

I would like to see an example problem with an algorithmic solution that runs in factorial time O(n!). The algorithm may be a naive approach to solve a problem but cannot be artificially bloated to run in factorial time.

Extra street-cred if the factorial time algorithm is the best known algorithm to solve the problem.

recursion.ninja
  • 4,968
  • 7
  • 42
  • 76
  • 2
    Finding all possible paths from source to destination in a directed acyclic graph ([DAG](https://en.wikipedia.org/wiki/Directed_acyclic_graph)). – Keyur Potdar Jul 24 '20 at 07:49

4 Answers4

56

Generate all the permutations of a list

You have n! lists, so you cannot achieve better efficiency than O(n!).

Divyanshu Maithani
  • 9,464
  • 1
  • 31
  • 41
zw324
  • 25,032
  • 15
  • 79
  • 112
  • 7
    @ziyao-wei Listing all combinations of a set is 2^n. See: http://en.wikipedia.org/wiki/Combination#Number_of_k-combinations_for_all_k . Perhaps you mean listing all permutations? i.e. given n items, how many ways can they be ordered/permuted in an n-length string? – ChaimKut May 15 '14 at 12:15
  • @ChaimKut: Weird, I sure meant permutations but the asker changed it into combinations, as per edit history. Reverting. – zw324 Mar 30 '15 at 19:22
  • 2
    This actually can be no better than `O(n * n!)` because you have `n!` lists and each one has `n` things in it. – btilly Dec 15 '20 at 17:35
27

Traveling Salesman has a naive solution that's O(n!), but it has a dynamic programming solution that's O(n^2 * 2^n)

Zim-Zam O'Pootertoot
  • 17,440
  • 4
  • 38
  • 67
6

List all permutations of an array is O(n!). Below is a recursive implementation using the swap method. The recursion is inside the for loop and the elements in the array are swapped in position until no more elements remain. As you can see from the result count, the number of elements in the array is n!. Each permutation is an operation and there are n! operations.

def permutation(array, start, result)
    if (start == array.length) then
        result << array.dup  
    end
    for i in start..array.length-1 do
        array[start], array[i] = array[i], array[start]
        permutation(array, start+1,result)
        array[start], array[i] = array[i], array[start]
    end 
    result   
end        


p permutation([1,2,3], 0, []).count  #> 6 = 3!
p permutation([1,2,3,4], 0, []).count #> 24 = 4!
p permutation([1,2,3,4,5], 0, []).count #> 120 = 5!
aarti
  • 2,565
  • 1
  • 20
  • 29
3

Here is a simple example with Big O( n! ):

This is in python 3.4

 def factorial(n):
    for each in range(n):
        print(n)
        factorial(n-1)
grepit
  • 16,512
  • 5
  • 83
  • 71