This question is regarding the Time Complexity of two algorithms.
So I am a solving a question involving two lists (not sorted) of integers, and I want to return the pair of integers (one from each list) with the smallest absolute difference.
The naive approach is simply to iterate through both lists, and keep track of the smallest difference throughout, and at the end return the pair that produced this difference- I believe this would take
O(mn) time, where n and m are the length of each list; as we simply use2x for loops.Another approach is to
sortboth lists, then iterate through both of them, and there is some logic where we can break out of the for loops in many instances without iterating through the whole of the second list. I believe this would takeO(nlogn + mlogm) time, again where n,m are the lengths of the two lists.
I read on the solution page that solution 2. is more efficient, but I don't see why?- if the time complexity I mentioned above are correct, for solution 2. if we factorise by mn what's left >0??