The method is:
List<Book> books = new List<Book>();
public List<Book> Shoot()
{
foreach(var b in books)
{
bool find = true;
foreach(var otherb in books)
{
if(otherb != b && otherb.Author == b.Author)
{
find = false;
}
}
if(find)
{
yield return b;
}
}
}
Normally, the time complexity will be O(books.Count^2), but there is a if(find)
statement in the outer loop and it may change the loop times.
So my questions are:
- What is the time complexity of this method?
- How did you calculate it?
I’m waiting online for your answer.
Thank you in advance.
You would go through each book in the outer loop (n) and for each outer book you would go through each otherb in the inner loop (n times) so the the time complexity would be O(n^2).
The yield return would not change the complexity of the algorithm, it creates an iterator pattern but if you traverse the whole list from the calling function, you go through all the iterations in your algo.
What is the yield keyword used for in C#?
To optimize the algorithm, as btilly mention, you could do two passes over the collection, on the first pass you store the number of books per author in a hash table and on the second pass you check if the author has more than one book using the hash table (assuming constant time for the lookup) and yield the book if it does:
This way you have a linear time complexity of O(n), note that you would need O(n) extra space in this case.