Program brought down to O(nlogn) complexity