I have a recursive algorithm with two nested for loops. I'm trying to figure out what the Big-O time complexity will be.
public Set<Person> getDistinctCombinedPersons(Collection<Person> persons) {
return permutatePersons(new ArrayList(persons), new HashSet<>(persons));
}
private Set<Person> permutatePersons(List<Person> personList, Set<Person> personSet) {
if(personList.isEmpty() {
return personSet;
}
Set<Person> deepCopyPersonSet = new HashSet<>(personSet);
for(Person lPerson : personList) {
for(Person sPerson : deepCopyPersonSet) {
Person uniquePerson = CombinePeople.combine(lPerson, sPerson);
personSet.add(uniquePerson);
}
}
personList.remove(personList.size()-1);
return permutatePersons(personList, personSet);
}
Assuming that you call permutatePersons
with a list of length N
the following recursion applies:
T(N) = T(N-1) + O(N^2)
That's because in every recursive step you call function with list of length N-1 (where N the current length) and also you do computations of total complexity O(N^2) (outer loop O(N) -just traversing list and inner loop traversing the hash map in O(N) -O(1) for each element and total N element, So the nested loops are overall O(N^2)).
You can easily see:
T(N) = T(N-1) + O(N^2) = T(N-2) + O(N^2) + O((N-1)^2) =...
= O(n(n+1)(2n+1)/6) = O(n^3)
Looks like it would be a big-O of n^2 for the nested loop:
for(Person lPerson : personList) {
for(Person sPerson : deepCopyPersonSet) {
Person uniquePerson = CombinePeople.combine(lPerson, sPerson);
personSet.add(uniquePerson);
}
}
You have to iterate over the each element for each element in the set.
And then the recursive call has a big O of n since it will call your method once for each element in the set.
Combining the two: n * n^2
will result in a big O of n^3
Because you have two nested loops you have the runtime complexity of O(m*n)
. It's because for n
- Person
s in deepCopyPersonSet
you iterate m
times. n
in this example is the quantity of Person
s in personList
.
Your code is basically:
for(int i = 0, i < m, i++)
for(int j = 0, j < n, j++)
//your code
For every iteration of m, we have n iterations of code
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.