Finally solved this one. O(NlogN)