In my experience, the only time you really NEED a sorted collection is when you must output the data in sorted order. For this problem I can think of a solution that runs in O(N) time and doesn't use sorting.
I mean to say that in merge sort algorithm we make a merge tree we find the answer while sorting. So can we do this problem like that.
And thank you for giving your time :)