I have a recursive function working on a list, the function contains a loop where itself is called, and ends up with another function g. Its structure is similar as follows, to simplify the issue, we can assume that l is always a list without duplicate elements.
let rec f l = function
| [] -> g ()
| _ ->
List.fold_left
(fun acc x ->
let lr = List.filter (fun a -> (a <> x)) l in
acc + (f lr))
1 l
I am not sure how to express the complexity of this function, with List.length l and the complexity of g.
I think it is proportional to the complexity of g and the factorial of List.length l, could anyone confirm?
Since you assume that the list
ldoes not contain any duplicates, what this function does is compute all sublists that have one less element than the original list and call itself recursively on all of them. So, the number of timesgis called when starting with a list of size n is g?(n) = n · g?(n-1) = n!Now, let’s consider everything else the function has to do. The amount of work at each step of the recursion includes :
So, since we know how many times each recursive step will be called (based on our previous analysis), the total amount of non-
grelated work is: t?(n) = n2 + n (n-1)2 + n (n-1) (n-2)2 + … + n!This formula looks like a pain, but in fact t?(n) / n! has a finite non-zero limit as n increases (it is the sum of the k+1 / k! with 0 < k < n) and so t?(n) = Θ(n!).