I want to post an interesting run time problem.
One problem goes as such: Given a length n list of lists of k ints, what is the most straight-forward way to check whether a given list of length k is equivalent to at least one of the lists (where same here implies that the order is also the same)?
For example:
input = [1,2,3], [[2,3,1], [2, 3,1]]
would give output = False
input = [1,1,2], [[2,2,1], [1,1,2]]
would give output = True
This is a very straight forward question. I can just compare the list 1 with list i where i ranges from 2 to n.
For each of the list comparisons, there are n elements to compare and thus you get n comparisons...
at the end, this is n*k comparisons.
So approx. I would say n*k time scale.
I want to modify the question to make it more interesting. What if you didn't care about the order? Suggest an efficient algorithm to do the comparison and discuss its time scale.
For me, the first idea that came to mind was to order the two lists using an efficient method. That would take it klogk time to sort and now I just need to make k comparisons so for each of the n elements (and the input list)... making it (n+1)*k^2*logk
But we know that sorting often slows things down. For example, is it faster to sort first and then find x or just find x?
To just find x, you need to say is x in list A? k comparisons, is x2 in A, k-1 and so forth. I get k(k-1)(k-2)... n times. k! comparisons n times.
so I get n*k!
Which is less than sorting first.
Can I do better? At first I wasn't sure. But I thought... I am looking for thing many items. It struck me then that I might be able to do better. What if I only sort the given list and look for elements in the long list in the sorted given list? Now:
O(n,k) = O_sorting_given_list + n*O_finding_k_elements_in_sorted_list
O(n,k) = k*log(k) + n*log(k)
now... O(n,k) = (k+n)*k*log(k)
which is better.
Is there a better way? I can't see it but I guess it doesn't mean it doesn't exist. This would make a very interesting test question. One problem I think with this course was that we didn't get interesting/sufficiently challenging problem sets (particularly in the latter half of the course) and the solutions are not very readily available. Working solution doesn't mean it's a great one and I would love to see alternate solutions.
No comments:
Post a Comment